Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace repeated char with something else in a string

Tags:

c#

I need help to figure out a logic:

So, let's say I have a string, and whenever there is a Char repeated inside that string, I need to replace it with a (Char + sequence of number).

For example:

Original String: "abcdefgabfabc"

Expected output: "abcdefga2b2f2a3b3c2"

'a' occurs 3 times, so the first 'a' remains as 'a', but the second 'a' becomes 'a2', and the third 'a' becomes 'a3' and the same goes to other chars like b, b2, b3...

like image 206
C.J. Avatar asked Feb 13 '23 18:02

C.J.


2 Answers

  1. Create a Dictionary of letters and the # of occurrences of each letter
  2. Create a StringBuilder to store the output
  3. Loop through the input string letter by letter
  4. Output the letter to the new string
  5. If a letter is not in the dictionary, add it as the key with a '1' as the value
  6. If a letter is already in the dictionary, increase the value by 1 and append the value to the output string
like image 94
D Stanley Avatar answered Feb 24 '23 17:02

D Stanley


Try this:

var foundChars = new SortedDictionary<char, int>();
var stringBuilder = new StringBuilder();

foreach (var c in originalString)
{
    var count = 0;

    if (!foundChars.TryGetValue(c, out count)
    {
        foundChars.Add(c, 1);
    }
    else
    {
        count += 1;
        foundChars[c] = count;
    }

    stringBuilder.Append(c);
    if (count > 0) stringBuilder.Append(count);
}

Note that while less pretty this will be more performant than LINQ based solutions and be retrocompatible with .NET 2.0.

like image 30
Crono Avatar answered Feb 24 '23 15:02

Crono