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

I want to find the last character of a string in C# and then put it in an if statement.

Then if the last character is equal to 'A', 'B' or 'C' a certain action should be performed.

How do I get the last character of a string in C#?

5

7 Answers

Use the EndsWith() method of strings:

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

Heres the MSDN article explaining this method:

(v=vs.71).aspx

I assume you don't actually want the last character position (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]

string is a zero based array of char.

char last_char = mystring[mystring.Length - 1];

Regarding the second part of the question, if the char is A, B, C

Using if statement

char last_char = mystring[mystring.Length - 1];
if (last_char == 'A' || last_char == 'B' || last_char == 'C')
{ //perform action here
}

Using switch statement

switch (last_char)
{
case 'A':
case 'B':
case 'C': // perform action here break
}
2

There is an index-from-end operator that looks like this: ^n.

var list = new List<int>();
list[^1] // this is the last element
list[^2] // the second-to-last element
list[^n] // etc.

The official documentation about indices and ranges describes this operator. One thing to be careful about: this operator can fail at runtime if there are not enough elements in the list (System.ArgumentOutOfRangeException).

With recent C# versions, one can just use Last() or LastOrDefault() on a string in C# to return last char.

string sample = "sample string";
char lastCharacter = sample.Last();
if (lastCharacter == 'A' || lastCharacter == 'B' || lastCharacter == 'C')
{ Console.WriteLine(lastCharacter);
}
else if (lastCharacter == 'g')
{ Console.WriteLine($"found! {char.ToUpper(lastCharacter)}");
}
else if (sample.EndsWith("ing"))
{ Console.WriteLine($"use for multiple characters! {sample}");
}
1

Since C# 8.0, you can use new syntactic forms for System.Index and System.Range hence addressing specific characters in a string becomes trivial. Example for your scenario:

var lastChar = aString[^1..]; // aString[Range.StartAt(new Index(1, fromEnd: true))
if (lastChar == "A" || lastChar == "B" || lastChar == "C") // perform action here

Full explanation here: Ranges (Microsoft Docs)

3

You can also get the last character by using LINQ, with myString.Last(), although this is likely slower than the other answers, and it gives you a char, not a string.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like