0

我需要一种算法帮助,该算法将为 C# 中的字符串列表中的重复元素添加索引。

IE

A, B, C, D, A, B, E, F, A

会变成

A, B, C, D, A (1), B (1), E, F, A (2)
4

3 回答 3

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

}

添加:

我基本上在做的是一次遍历一个字符的数组。我在字典中记录“我看到每个字符的次数”——每次看到一个新字符时我都会增加。

当我看到一个我已经看过的 - 我按照要求在括号中添加数字。

于 2012-10-25T13:40:20.523 回答
1

使用兰巴/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);
于 2012-10-25T14:24:15.130 回答
0
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);
}
于 2012-10-25T13:46:17.550 回答