为什么C#的IndexOf搜索空字符会返回零?

4

以下是我使用 .NET Core 6 的示例代码:

using System;

namespace testTerminator
{
    class Program
    {
        static void Main(string[] args)
        {
            // Given an array of bytes:
            byte[] array = {72, 101, 108, 108, 111, 0, 0, 32, 72, 101};
            // Converted to a string:
            string data = System.Text.Encoding.ASCII.GetString(array);
            
            // Why does the following line not return the position
            // of the null characters?
            int terminator = data.IndexOf("\0\0");  // returns 0

            // Output:
            Console.WriteLine("Data is '{0}'", data);
            Console.WriteLine("Found terminator at {0}", terminator);

            // Verify null characters are still in the data string:
            byte[] dataBytes = System.Text.Encoding.ASCII.GetBytes(data);
            for (int i = 0; i<dataBytes.Length; i++){
                Console.Write("{0},", dataBytes[i]);
            }
            Console.WriteLine();
        }
    }
}

这会导致以下输出:
Data is 'Hello He'
Found terminator at 0
72,101,108,108,111,0,0,32,72,101,

为什么在空字符位于位置6时,IndexOf("\0\0")返回零?

2
似乎是一个bug。在dotnetfiddle上,Roslyn和.NET 4.7.2编译器都产生了预期的结果,但.NET 6没有。 - Sweeper
1
@Sweeper - 我开始觉得你是正确的。我已经在几个在线编译器上尝试过了,大多数都获得了成功的结果。也许这只是一个 bug。 - habadeer
@Sweeper 我无法重现这个问题(.Net 6 / C# 10)。在这里发布的代码返回了预期的结果。你在哪里测试它了? - Jimi
@Jimi https://dotnetfiddle.net/90K1Dp - Sweeper
@Sweeper 不是一个错误,正如AndrewS所指出的那样。 - Charlieface
显示剩余2条评论
2个回答

2
如评论中所提到的AndrewS},{{link2:Microsoft有文档记录这一点。默认情况下使用当前区域设置,如果该区域设置存在被忽略的字符,则返回0。在 .Net 5 中,Unicode 库已更改,从而影响了此功能。
请注意,您可以使用简单的一行代码重现此问题:
Console.WriteLine("abc\0".IndexOf("\0"));

要解决这个问题,你需要使用一个序数比较。
int terminator = data.IndexOf("\0\0", StringComparison.Ordinal);  // returns 0

有趣的是,当你使用 char 版本时,它不会这样做。
Console.WriteLine("abc\0".IndexOf('\0'));

返回值为3。这是因为默认情况下它执行的是序数比较。{{link1}}

哇,我从未想过\0与文化有任何关系。 - Sweeper

0

由于我的声望低于50,我无法发表评论。

我在我的vs 2019社区版中尝试了你的代码并使用Net Core 3.1运行,输出如下:

" 数据是 'Hello He' 在第5个位置找到终止符 72,101,108,108,111,0,0,32,72,101, "

虽然不是什么大问题,但你可能想尝试使用不同版本的Net Core。

最好的祝福,


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接