一个含有字符串的数组,例如:["a","b","a","c","b","d","a"],需要得到一个新数组 ["a1","b1","a2","c","b2","d","a3"] c#
时间: 2024-06-02 22:04:45 浏览: 79
C# 字符串
你可以通过遍历原数组,并使用 Dictionary 来统计每个字符串出现的次数,然后再次遍历原数组,根据每个字符串出现的次数,构造新的字符串数组。以下是一个示例代码:
```
string[] originalArray = new string[] { "a", "b", "a", "c", "b", "d", "a" };
Dictionary<string, int> countDict = new Dictionary<string, int>();
string[] newArray = new string[originalArray.Length];
// 统计每个字符串出现的次数
for (int i = 0; i < originalArray.Length; i++)
{
string str = originalArray[i];
if (countDict.ContainsKey(str))
{
countDict[str]++;
}
else
{
countDict[str] = 1;
}
int count = countDict[str];
newArray[i] = str + count;
}
// 输出新的字符串数组
foreach (string str in newArray)
{
Console.Write(str + " ");
}
```
阅读全文