Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the last character of a string in C#?

Tags:

c#

I want to find the last character of a string and then put in an if stating that if the last character is equal to "A", "B" or "C" then to do a certain action. How do I get the last character?

like image 765
esq619 Avatar asked Feb 10 '13 03:02

esq619


2 Answers

Use the endswith method of strings:

if (string.EndsWith("A") || string.EndsWith("B")) {     //do stuff here } 

Heres the MSDN article explaining this method:

http://msdn.microsoft.com/en-us/library/system.string.endswith(v=vs.71).aspx

like image 192
Unicorno Marley Avatar answered Oct 01 '22 21:10

Unicorno Marley


I assume you don't actually want the last character position (which would be yourString.Length - 1), but the last character itself. You can find that by indexing the string with the last character position:

yourString[yourString.Length - 1] 
like image 30
icktoofay Avatar answered Oct 01 '22 21:10

icktoofay