Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C# strings end with empty string?

Tags:

string

c#

.net

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 :)
like image 795
nan Avatar asked Jan 10 '11 13:01

nan


People also ask

Do while loop examples in C?

Syntax. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.

Why is do used in C?

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once.

What is do command in C?

Syntax. iteration-statement: do statement while ( expression ) ; The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore, the body of the loop is always executed at least once. The expression must have arithmetic or pointer type.


2 Answers

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.

like image 187
Oded Avatar answered Oct 13 '22 00:10

Oded


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.

like image 41
Pabuc Avatar answered Oct 12 '22 23:10

Pabuc