Helping Hands
Helping Hands

Reputation: 5396

Unable to get last character of string

enter image description here

** Code: **

String test = "32132SSS654";
char Lastchar = test[test.Length - 1];

Assert.IsTrue((Lastchar).Equals("4"));

I am trying to get the last character from the string then doing assert but it returns me something extra like 52 with the last character 4 and that's why my assert getting fail.

Upvotes: 0

Views: 164

Answers (4)

Souvik Ghosh
Souvik Ghosh

Reputation: 4606

52 is the ASCII value of the character- 4 and you are comparing it wrongly to "4" which is a string type.

In C#, when you enclose a value in double quotes that is a string value. When you put them in single quotes that becomes a char value and within single quotes you can put any single char value.

Change your code to-

Assert.IsTrue((Lastchar).Equals('4'));

Assert not only compares the value but also compares the type of the object whether they are equal. So just in case if you compare something like-

Assert.IsTrue((4).Equals('4'));

would return false since it compares int value to a char value which would never be equal.

Upvotes: 1

Markus
Markus

Reputation: 22456

The problem is that in your Equals call you are comparing the char to a string ("4"):

char Lastchar = test[test.Length - 1];
Assert.IsTrue((Lastchar).Equals("4"));

This returns false because the types differ. If you compare to a char of '4' it will return true:

Assert.IsTrue((Lastchar).Equals('4'));

Upvotes: 2

Jamiec
Jamiec

Reputation: 136094

The last character is a char not a string:

Assert.IsTrue((Lastchar).Equals('4'));

(char literals use single quotes).

The 52 is the ASCII value for the character "4"

Upvotes: 3

ViRuSTriNiTy
ViRuSTriNiTy

Reputation: 5155

The value of Lastchar is correct. 52 is the decimal representation / value for the character 4 (see ASCII table). It's just a debug specific display.

Upvotes: 2

Related Questions