我可以在 c# 中做这样的事情来确定字符串长度吗?

Can i determine string length in c# doing something like this?

出于好奇,我试图在不使用属性或方法的情况下确定字符串长度,这在 C 中有效,但对于 [= 11=]

根据我的理解,我说的是C,这个字符是在给某个字符串设置值后自动放入的东西,这样就可以确定多少存储需要 space,但这在 C# 中如何工作?

string str = "someText";
int lenght = 0;
while (str[lenght]!='[=10=]')
{
    lenght++;
}
Console.WriteLine(str);
Console.WriteLine("String lenght is : "+ lenght);
Console.ReadLine();

A string is an object of type String whose value is text. 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 ('[=12=]'). The Length property of a string represents the number of Char objects it contains, not the number of Unicode characters. To access the individual Unicode code points in a string, use the StringInfo object.

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/

C# 字符串没有终止符。相反,它们的实际长度与文本本身一起存储。这叫做length-prefixed strings.

您可以使用 Length 属性.

访问长度

这是 C# 代码

    string str = "someText";
    int lenght = 0;

    foreach (char c in str)
    {
        lenght++;
    }
    Console.WriteLine(str);
    Console.WriteLine("String lenght is : "+lenght);
    Console.ReadLine();

在 C 中,nul 字符终止作为字符数组处理的字符串是标准库支持的约定。它不是语言本身的一部分。请注意,在设置 C 字符串值时,"automatically" 无需放置 nul 字符,它由库和常量编译器处理。

C# 不使用以 nul 结尾的字符串,因此 none 适用。

将字符串视为抽象的字符序列。有多种方法可以在计算机库中实现这样的序列。以下是一些示例:

  • 空字符终止 - 字符序列以特殊字符值 '[=10=]' 终止。 C 使用此表示法。
  • Character-terminated - 这类似于 null-terminated,但使用了不同的特殊字符。这种表示现在很少见了。
  • 长度前缀 - 字符串的前几个字节用于存储其长度。 Pascal 使用了这种表示。
  • 长度和字符数组 - 此表示将字符串存储为具有字符数组的结构,并将长度存储在单独的区域中。

混合表示也是可能的,例如将以 null 结尾的字符串存储在长度和数组表示中。

C# 使用长度前缀和空终止字符串的组合,并且还允许在字符串中嵌入空字符。但是,这并不意味着您可以访问空终止符或长度字节,因为与 C 不同,C# 执行绑定检查,并在尝试访问超过字符串末尾时抛出异常。