小编Tri*_*ong的帖子

为什么在使用 IndexOf(string) 和 IndexOf(char) 时,非组合变音符号前面的空格会产生不同的作用?

我正在从一个带有空格后的非组合变音符号的字符串中创建一个子字符串。这样做时,我检查字符串,.Contains()然后执行子字符串。当我char在 an 中使用空格时.IndexOf(),程序按预期执行,但是当使用字符串“”时,.IndexOf()程序中会引发异常。如下面的示例所示,只有string主要重音变音符号 (U+02C8) 之前的 a 会抛出ArgumentOutOfRangeException.

简单代码(由 John 建议编辑):

string a = "a? pr??z?nt";
string b = "ma? ?pr?znt";

// A            
Console.WriteLine(a.IndexOf(" ")); // string index:  2
Console.WriteLine(a.IndexOf(' ')); // char index:    2

// B    
Console.WriteLine(b.IndexOf(" ")); // string index: -1
Console.WriteLine(b.IndexOf(' ')); // char index:    3
Run Code Online (Sandbox Code Playgroud)

我测试的示例代码:

        const string iPresent = "a? pr??z?nt",
                     myPresent = "ma? ?pr?znt";

        if(iPresent.Contains(' '))
        {
            Console.WriteLine(iPresent.Substring(0, iPresent.IndexOf(' ')));
        } …
Run Code Online (Sandbox Code Playgroud)

c# string unicode substring indexof

7
推荐指数
1
解决办法
69
查看次数

标签 统计

c# ×1

indexof ×1

string ×1

substring ×1

unicode ×1