So this is the solution where you have only one letter within your string. You need to find the letter that is within the string, if it exists, and find its index. Then you have to insert the respective value instead of the letter, obtained from the dictionary.
String mystring = "1453400e0000875";
Dictionary<char, string> pairs = new Dictionary<char, string>();
pairs.Add('a', "09001");
pairs.Add('b', "09002");
pairs.Add('c', "09003");
pairs.Add('d', "09004");
pairs.Add('e', "09005");
//...
char letter = mystring.FirstOrDefault(a => Char.IsLetter(a));
if (letter != '\0')
{
int index = mystring.IndexOf(letter);
string substitute;
pairs.TryGetValue(mystring[index], out substitute);
mystring = mystring.Substring(0, index) + substitute + mystring.Substring(index + 1);
}
EDIT:
Using Replace method of the string, the if
part can be altered like this:
char letter = mystring.FirstOrDefault(a => Char.IsLetter(a));
if (letter != '\0')
{
string substitute;
pairs.TryGetValue(letter, out substitute);
mystring = mystring.Replace(letter.ToString(), substitute);
}
EDIT2:And if I didn't understand the OP correctly so that he wants to remove the letter and add the replacement string to the end of the source string, the if
statement should be like this:
if (letter != '\0')
{
string substitute;
pairs.TryGetValue(letter, out substitute);
mystring = mystring.Replace(letter.ToString(), "");
mystring += substitute;
}
and this is the generalisation when you have more letters within the string. It is the similar solution but requires to iterate over all the letters within the string.
String mystring = "1453a400e0000b875";
Dictionary<char, string> pairs = new Dictionary<char, string>();
pairs.Add('a', "09001");
pairs.Add('b', "09002");
pairs.Add('c', "09003");
pairs.Add('d', "09004");
pairs.Add('e', "09005");
//...
var lettersList = mystring.Where(a => Char.IsLetter(a));
foreach (char letter in lettersList)
{
int index = mystring.IndexOf(letter);
string substitute;
pairs.TryGetValue(mystring[index], out substitute);
mystring = mystring.Substring(0, index) + substitute + mystring.Substring(index + 1);
}
Checked and it works!