Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

.net - Do C# strings end with empty string?

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 :)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...