为什么C#ToLower不更改字符串的ASCII值?

为什么C#ToLower不更改字符串的ASCII值?,c#,string,C#,String,我试图创建一个方法来查找字符串中重复字符的数量。因此,例如,DuplicateCount(“aabbcde”)将返回2,DuplicateCount(“aabbcde”)也将返回2。创建此方法的第一个想法是将整个字符串转换为小写,然后根据ASCII值计算字符出现的次数。这是我的代码: public static int DuplicateCount(string str) { int[] buffer = new int[128]; //128 possible ASCII charac

我试图创建一个方法来查找字符串中重复字符的数量。因此,例如,
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;
}
publicstaticintduplicateCount(stringstr)
{
int[]buffer=new int[128];//128个可能的ASCII字符
字符串下限=str.ToLower();
int-dups=0;
对于(int i=0;i

当字符串包含大写字符时,此方法无效。此方法不起作用的原因是,调用
str.ToLower()
不会更改字符的ASCII值,即使字符串本身已更改为所有小写。有人知道为什么会这样吗?你会如何处理它呢?

这种情况发生是因为你在循环中使用了
str
而不是
lower
ToLower()
仅返回修改后的字符串的副本(您显然保存了该字符串,但未使用该字符串)。

公共静态int DuplicateCount(string str){
字符串strLower=str.ToLower();
int-dups=0;
for(int i=0;i
字符串是不可变的。您正在比较两个不同的对象。是因为行
intnum=(int)str[i]应该是
intnum=(int)下[i]
?@yinnonsanders-是的,
循环的
也应该检查
较低的长度。@yinnonsanders这一定是真的吗?
Length
属性给出字符串中UTF-16代码单元的数量,而不是实际字符或代码点的数量。Unicode中有很多奇怪的东西让我怀疑
ToLower
是否一定会保持
Length
属性不变。@Kyle根据
Length
的说法是一样的,但这是一个有趣的问题。
int num=(int)lower[i]
@BrandonMinner也许你应该使用一个工具,告诉你一些不完整的想法,比如给变量赋值,然后不使用那个值和调试器。
public static int DuplicateCount(string str) {
    string strLower = str.ToLower();
    int dups = 0;

    for (int i = 0; i < strLower.Length; i++)
    {
        int num1 = (int)strLower[i];

        for (int j = i+1; j < strLower.Length - 1; j++ ) {
            int num2 = (int)strLower[j];

            if(num1 == num2) {
               dups++; // found
            }
            else{
               break; // not found
            }
        }
    }
    return dups;
}