SuicideSheep
SuicideSheep

Reputation: 5550

C# weird string behaviour?

I have a string variable as below:

string testVar = "abc ";

Then I have a if statement as below:

if(this.testVar[this.testVar.Length-1].Equals(" "))

From the above I'm trying to find if the last character is space, if it is space then do something. But it is always false even if my testVar = "abc "?

Upvotes: 1

Views: 225

Answers (4)

Kris Vandermotten
Kris Vandermotten

Reputation: 10201

It is always false because a char is never equal to a string.

This would work:

if (this.testVar[this.testVar.Length-1].Equals(' '))

or this

if (this.testVar[this.testVar.Length-1] == ' ')

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545995

testVar[…] returns a char, not a string. That’s why an Equals test with a string always returns false. You can fix this easily by comparing to a char. you also don’t need Equals:

if (testVar[testVar.Length - 1] == ' ')

It is worth nothing that, if you had used == initially instead of Equals, you would have gotten a compile time error explaining the problem. This illustrates nicely why it’s good to use early binding rather than late binding (Equals takes an object and hence doesn’t offer compile-time type checking).

Upvotes: 9

Ashouri
Ashouri

Reputation: 906

check this dude

var result = str.Substring(str.LastIndexOf(' ') + 1);

Upvotes: 0

Andrew
Andrew

Reputation: 2335

Why do you not just use:

if (testVar.EndsWith (" ")) 

Upvotes: 4

Related Questions