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

时间:2017-07-24 19:30:49

标签: c# string

我试图创建一种方法来查找字符串中重复字符的数量。因此,例如,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值,即使字符串本身已更改为全部小写。有谁知道为什么会这样?你会如何解决它?

2 个答案:

答案 0 :(得分:11)

这是因为您在循环中使用了str而不是lowerToLower()仅返回已修改字符串的副本(您显然已保存,但未使用)。

答案 1 :(得分:0)

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