Search code examples
c#linqgeneric-collections

check if string contains dictionary Key -> remove key and add value


I am stuck at a function which checks a string ('14534000000875e') if it contains a letter. If it contains a letter (a-z), remove the letter and add a string to the end.

To realize this, I have created a Dictionary<char, string> Pairs which has mapped a to 09001, b to 09002 [...] and z to 09026

This is my code so far:

public static string AlterSerial(string source)
{
    Dictionary<char, string> pairs = new Dictionary<char, string>();
    pairs.Add('a', "09001");
    ...

    int index = source.IndexOf(x);
    if (index != -1)
    {
        return source.Remove(index, 1);
    }
    return source;
}

How can I check if the source string contains one of the 26 keys, delete this key and add the corresponding string to the end of the source-string?

Note: the letter is not always at the end of the source.

Kind regards


Solution

  • Try this:

    Dictionary<char, string> pairs = new Dictionary<char, string>();
    pairs.Add('a', "09001");
    ...
    
    foreach(KeyValuePair<string, string> entry in pairs)
    {
        if (source.Contains(entry.Key))  // .Key must be capitalized
        {
          source = source.Replace(entry.Key, "") + entry.Value;
          break;
        }
    }
    
    return source;
    ....