【问题标题】:Why does C# .ToLower not change the ASCII value of the string?为什么 C# .ToLower 不改变字符串的 ASCII 值?
【发布时间】: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 是一样的,但这是一个有趣的问题。

标签: c# string


【解决方案1】:

发生这种情况是因为您在循环中使用了str 而不是lowerToLower() 只返回一个修改过的字符串的副本(你显然保存了,但没有使用)。

【讨论】:

  • int num = (int)lower[i];
  • @BrandonMinner 也许你应该使用一个工具来告诉你不完整的想法,比如给一个变量赋值然后不使用那个值——还有一个调试器。
【解决方案2】:
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;
}

【讨论】:

    猜你喜欢
    • 2012-09-12
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2019-11-12
    • 2015-09-14
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多