gpt4 book ai didi

c# - C#中的字符串结尾

转载 作者:太空宇宙 更新时间:2023-11-03 17:40:45 24 4
gpt4 key购买 nike

字符串存入内存时是否以\0字符结尾?编译器如何知道结束??

如果是真的

Console.WriteLine(str.LastIndexOf('\0'));

必须返回长度,但输出为= -1

最佳答案

来自 MSDN

Internally, the text is stored as a sequential read-only collection of Char objects. There is no null-terminating character at the end of a C# string; therefore a C# string can contain any number of embedded null characters ('\0').

此外,来自 Jon Skeet 的 Strings in .NET and C#

Although strings aren't null-terminated as far as the API is concerned, the character array is null-terminated, as this means it can be passed directly to unmanaged functions without any copying being involved, assuming the inter-op specifies that the string should be marshalled as Unicode.

简而言之,内部字符数组确实以 \0 结尾,但 API(例如,LastIndexof)会忽略它。

此外,如果您手动插入 \0 在 c# 字符串的中间(例如,Hello\0World),C# 字符串API 会忽略它,但其他 API 可能不会并最终忽略第一个 \0 之后的所有内容(例如,World)。

查看 reference source

public override int GetHashCode() {
//...
Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
//...
}

关于c# - C#中的字符串结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com