【发布时间】:2017-07-24 19:30:49
【问题描述】:
我试图创建一种方法来查找字符串中重复字符的数量。因此,例如,DuplicateCount("aabbcde") 将返回 2,DuplicateCount("aabBcde") 也将返回 2。创建此方法的第一个想法是将整个字符串转换为小写,然后根据字符的 ASCII 值计算字符出现的次数。所以这是我的代码:
public static int DuplicateCount(string str)
{
int[] buffer = new int[128]; //128 possible ASCII characters
string lower = str.ToLower();
int dups = 0;
for (int i = 0; i < str.Length; i++)
{
int num = (int)str[i];
buffer[num]++; //increase
if (buffer[num] == 2)
{
dups++;
}
}
return dups;
}
当字符串包含大写字符时,此方法将不起作用。此方法不起作用的原因是str.ToLower() 调用不会更改字符的 ASCII 值,即使字符串本身已全部更改为小写。有谁知道为什么会这样?你将如何解决它?
【问题讨论】:
-
字符串是不可变的。您正在比较两个不同的对象。
-
是不是因为
int num = (int)str[i];这行应该是int num = (int)lower[i];? -
@yinnonsanders - 是的,
for循环也应该检查lower.Length。 -
@yinnonsanders 这一定是真的吗?
Length属性给出了字符串中 UTF-16 代码单元的数量,而不是实际字符或代码点的数量。 Unicode 中有足够多奇怪的东西让我怀疑ToLower是否一定会让Length属性保持不变。 -
@Kyle 根据stackoverflow.com/questions/20301347/…
Length是一样的,但这是一个有趣的问题。