Replace re-char with something else in the line

I need help to figure out the logic:

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

For example:

Original line: "abcdefgabfabc"

Expected Result: "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 applies to other characters like b, b2 , b3 ...

+4
source share
5 answers
var str = "abcdefgabfabc";
var chars = str.Select((c, index) =>
        {
            int count = str.Substring(0, index).Count(x => c == x);
            if (count > 0) return c.ToString() + (count+1);
            else return c.ToString();
        }).SelectMany(c => c).ToArray();
var result = new string(chars); // abcdefga2b2f2a3b3c2
0
source
  • Create Dictionaryletters and the number of occurrences of each letter
  • Create StringBuilderto save output
  • , "1"
  • , 1
+7

:

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);
}

, , , LINQ, .NET 2.0.

+1

LINQ , , .

..

var count = new Dictionary<string, int>();
var string = "abcdefabcdef";
var result = "";

string.Select().Each(c => {
    if (count.ContainsKey(c)) 
        count.Add(c, 1);
    else
        count[c]++;
    result += count[c] > 1? c + count[c] : c;
});
0

Some of the other answers suffer from O(n^2)( Selman22 , Stumblor ) or O(n*log n)( Chrono1981 ), although the solution O(n)is simple. The right decision is really what D Stanley is , and I hinted. Here it is:

var input = "abcdefgabfabc";
var counts = new Dictionary<char, int>();

var sb = new StringBuilder();

foreach (var c in input)
{
    int count;
    counts.TryGetValue(c, out count);  // If "counts" doesn't have the key, then count will be 0
    counts[c] = ++count;

    sb.Append(c);

    if (count > 1)
        sb.Append(count);
}

var result = sb.ToString();
0
source

Source: https://habr.com/ru/post/1527372/


All Articles