【发布时间】:2023-01-24 16:04:43
【问题描述】:
我有一串数字,我想计算该字符串有多少个数字。
例子:
111222
1002345
000000
预期输出:
111222 2
1002345 6
000000 1
我使用以下代码实现了这一点:
private static int Counter(string ID)
{
char[] numbers = new char[]{'0','1','2','3','4','5','6','7','8','9'};
List<int> listofmatched = new List<int>();
var split = ID.ToArray();
foreach (var num in split)
{
if (numbers.Contains(num))
{
if (listofmatched.Contains(num))
{
continue;
}
else
{
listofmatched.Add(num);
}
}
}
return listofmatched.Count;
}
有什么办法可以改进上面的代码吗?我觉得有不必要的循环
【问题讨论】: