Reputation: 15
I need help with an algorithm that will add an index to the duplicate elements in a string list in C#.
i.e.
A, B, C, D, A, B, E, F, A
will become
A, B, C, D, A (1), B (1), E, F, A (2)
Upvotes: 0
Views: 330
Reputation: 26386
Using Lamba/LINQ
string x = "A, B, C, D, A, B, E, F, A";
x = x.Replace(" ", "").Replace(",", ""); //Remove the spaces and commas
var l = x.Select((v, i) => String.Format("{0}({1})", v, x.Substring(0, i).Count(c => c.Equals(v))));
var s = l.Select(c=>c.Replace("(0)","")).ToArray();
string result = String.Join(", ", s);
Upvotes: 1
Reputation: 2233
var strings = new string[] { "A", "B", "C", "D", "A", "B", "E", "F", "A" };
Dictionary<string, int> counts = new Dictionary<string, int>();
for (int i = 0; i < strings.Length; ++i)
{
if (counts.ContainsKey(strings[i]))
strings[i] = string.Format("{0} ({1})", strings[i], counts[strings[i]]++);
else
counts.Add(strings[i], 1);
}
Upvotes: 0
Reputation: 4328
Dictionary<char,int> counts = new Dictionary<char,int>();
foreach (char c in myCharArray)
{
if (counts.Keys.Contains(c))
{
counts[c]++;
myOutputList.Add(c + "(" + counts[c] + ")");
}
else
{
counts.Add(c,0);
}
}
Added:
What I'm basically doing is going through the array one character at a time. I'm keeping a count of 'times I've seen each character' in the dictionary - which I increment every time I see a new one.
When I see one which I've seen already - I add the number in brackets as requested.
Upvotes: 2