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...
Dictionary
of letters and the # of occurrences of each letterStringBuilder
to store the outputTry 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With