Reputation: 5550
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
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
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
Reputation: 906
check this dude
var result = str.Substring(str.LastIndexOf(' ') + 1);
Upvotes: 0