出于好奇只是一个简短的问题.
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 :)
Run Code Online (Sandbox Code Playgroud)
Ode*_*ded 17
确定此字符串实例的结尾是否与指定的字符串匹配.
所有字符串将""
在末尾匹配...或字符串的任何其他部分.为什么?因为从概念上讲,每个角色周围都有空字符串.
"" + "abc" + "" == "abc" == "" + "a" + "" + "b" + "" + "c" + ""
Run Code Online (Sandbox Code Playgroud)
更新:
关于你的最后一个例子 - 记录在LastIndexOf
:
如果value为String.Empty,则返回值是此实例中的最后一个索引位置.
一个相关的问题是使用null作为字符串终止符 - 它发生在C和C++中,但不是C#.
来自MSDN - String Class (System)
:
在.NET Framework中,String对象可以包含嵌入的空字符,这些字符计为字符串长度的一部分.但是,在某些语言(如C和C++)中,空字符表示字符串的结尾; 它不被视为字符串的一部分,不计入字符串长度的一部分.
试试这个:
string str = "string";
Console.WriteLine(str.EndsWith(string.Empty)); //true
Console.WriteLine(str.LastIndexOf(string.Empty) == str.Length-1); // true
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
所以是的,正如Oded所说,他们总是匹配.