c# - string.Empty.StartsWith(((char)10781).ToString()) 总是返回 true?

标签 c# .net string unicode char

我试图处理以下字符:⨝ ( http://www.fileformat.info/info/unicode/char/2a1d/index.htm )

如果你检查一个以这个字符开头的空字符串,它总是返回true,这没有任何意义!这是为什么?

// visual studio 2008 hides lines that have this char literally (bug in visual studio?!?) so i wrote it's unicode instead.
char specialChar = (char)10781;
string specialString = specialChar.ToString();

// prints 1
Console.WriteLine(specialString.Length);

// prints 10781
Console.WriteLine((int)specialChar);

// prints false
Console.WriteLine(string.Empty.StartsWith("A"));

// both prints true WTF?!?
Console.WriteLine(string.Empty.StartsWith(specialString));
Console.WriteLine(string.Empty.StartsWith(((char)10781).ToString()));

最佳答案

您可以使用 ordinal StringComparison 修复此错误:

来自 MSDN 文档:

When you specify either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, the string comparison will be non-linguistic. That is, the features that are specific to the natural language are ignored when making comparison decisions. This means the decisions are based on simple byte comparisons and ignore casing or equivalence tables that are parameterized by culture. As a result, by explicitly setting the parameter to either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, increases correctness, and becomes more reliable.

    char specialChar = (char)10781;


    string specialString = Convert.ToString(specialChar);

    // prints 1
    Console.WriteLine(specialString.Length);

    // prints 10781
    Console.WriteLine((int)specialChar);

    // prints false
    Console.WriteLine(string.Empty.StartsWith("A"));

    // prints false
    Console.WriteLine(string.Empty.StartsWith(specialString, StringComparison.Ordinal));

关于c# - string.Empty.StartsWith(((char)10781).ToString()) 总是返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1893108/

相关文章:

c# - 多线程环境下的mysql连接器

c# - mvc post action json 未解析为参数

c# - 将 DataTable 内容导出到 CSV 文件

c# - 如何从 Owin 获取原始 url?

c# - Directory.Delete()/.Create() 是同步的吗?

c++ - c_str == string 与 c_str == c_str 的值相等

C#:for 循环初始化部分声明的变量范围的定义?

.net - .NET 中的分布式共享内存

javascript - 使用用于拆分的相同分隔符加入字符串

java - 在 Java 中分割正则表达式并捕获匹配的分隔符表达式?