Do C# strings end with empty string?

后端 未结 4 1252
再見小時候
再見小時候 2020-12-20 11:47

Just a short question out of curiosity.

string str = \"string\";
Console.WriteLine(str.EndsWith(string.Empty));                  //true
Console.WriteLine(st         


        
相关标签:
4条回答
  • There's a some more information in this question and its answers.

    In particular, "Indeed, the empty string logically occurs between every pair of characters."

    0 讨论(0)
  • 2020-12-20 12:08

    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.

    0 讨论(0)
  • 2020-12-20 12:13

    Try this:

    string str = "string";
    Console.WriteLine(str.EndsWith(string.Empty));                  //true 
    Console.WriteLine(str.LastIndexOf(string.Empty) == str.Length-1); // true
    Console.ReadLine();
    

    So yes as Oded said, they do always match.

    0 讨论(0)
  • 2020-12-20 12:19

    Think about it this way: LastIndexOf is kind of meaningless with an empty string. You could say the empty string exists at every index within a string, between each character. The documentation thus provides a definitive answer for what should be returned:

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

    At least in this case it returns an actual index. If it returned the string's length (representing the index "after" the end, which I believe was your point) it would be returning a result for a method called LastIndexOf that isn't even an index.

    And here's another way of looking at it: If I have this:

    Dim index As Integer = str.LastIndexOf("")
    

    ...then I should be able to do this:

    Dim substr As String = str.Substring(index, "".Length)
    

    ...and get "" back. Sure enough, when LastIndexOf returns the last index in the string, it works. If it returned the string's length, I'd get an ArgumentOutOfRangeException. Edit: Well, looks like I was wrong there. Hopefully my first point was strong enough on its own ;)

    0 讨论(0)
提交回复
热议问题