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

标签 c#

字符串存入内存时是否以\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/

相关文章:

c# - 使用 CreateFile 打开目录

c# - 使用 Task.Factory.StartNew() 后是否需要 Wait()?

c# - 高级文件读取

c# - 在枚举参数中使用短划线 (-) 字符

c# - 匹配字符串中所有模式的最佳方法?

c# - 如何创建一个对象的实例?

c# - 如何在 ModuleBuilder 中定义全局字段

c# - nhtmlunit javascript 不工作

c# - 禁用控件的文本颜色 - 如何更改它

c# - 如何消除两个类之间的依赖?