难道C#字符串结尾空字符串? [英] Do C# strings end with empty string?

查看:158
本文介绍了难道C#字符串结尾空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 字符串str =字符串;
Console.WriteLine(str.EndsWith(的String.Empty)); //真正
Console.WriteLine(str.LastIndexOf(的String.Empty)== str.Length); //假
//当然串是从0开始的索引,
//只写了,如果为了好玩,检查空字符串是否可以得到一些额外的指标
///莫名其妙地被一个奇迹:)

//最后

Console.WriteLine(str.LastIndexOf(的String.Empty)
               == str.LastIndexOf('G')); //真正 :)
 

解决方案

<一个href="http://msdn.microsoft.com/en-us/library/system.string.endswith.aspx"><$c$c>EndsWith:

  

确定此字符串实例的结尾是否与指定的字符串匹配。

所有字符串将匹配在最后...或者绳子的另一部分。为什么?因为概念上,还有身边的每一个字符空字符串。

 +ABC+==ABC= =+一++B++C+ 
 


更新:

关于你的最后一个例子 - 这是记录在 LastIndexOf

  

如果值的String.Empty,则返回值是在这种情况下,最后一个索引位置。


一个相关的问题是使用空作为一个字符串结束 - 这发生在C和C ++,但不是C#

从MSDN - String类(系统)

  

在.NET Framework中,一个String对象可以包括嵌入的空字符,这算不算字符串的长度的一部分。然而,在某些语言中,例如C和C ++,一个空字符表示字符串的结束;它不被认为是字符串的一部分,不计入该字符串的长度的一部分。

Just a short question out of curiosity.

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.

All strings will match "" at the end... or any other part of the string. Why? Because conceptually, there are empty strings around every character.

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


Update:

About your last example - this is documented on LastIndexOf:

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


A related issue is the use of null as a string terminator - which happens in C and C++, but not C#.

From 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#字符串结尾空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆