gpt4 book ai didi

c# - C# 字符串是否以空字符串结尾?

转载 作者:IT王子 更新时间:2023-10-29 04:48:57 30 4
gpt4 key购买 nike

出于好奇,只是一个简短的问题。

string str = "string";
Console.WriteLine(str.EndsWith(string.Empty)); //true
Console.WriteLine(str.LastIndexOf(string.Empty) == str.Length); //false
//of course string are indexed from 0,
//just wrote if for fun to check whether empty string get some extra index
///somehow by a miracle:)

//finally

Console.WriteLine(str.LastIndexOf(string.Empty)
== str.LastIndexOf('g')); //true :)

最佳答案

EndsWith :

Determines whether the end of this string instance matches the specified string.

所有字符串都将匹配末尾的 ""... 或字符串的任何其他部分。为什么?因为从概念上讲,每个字符周围都有空字符串。

"" + "abc" + "" == "abc" == "" + "a" + "" + "b" + "" + "c" + ""

更新:

关于您的最后一个示例 - 这记录在 LastIndexOf 上:

If value is String.Empty, the return value is the last index position in this instance.


一个相关的问题是使用 null 作为字符串终止符 - 这发生在 C 和 C++ 中,但不是 C#。

来自 MSDN - String Class (System) :

In the .NET Framework, a String object can include embedded null characters, which count as a part of the string's length. However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length.

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

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