'How to check the last character of a string in 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?



Solution 1:[1]

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]

Solution 2:[2]

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
}

Solution 3:[3]

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).

Solution 4:[4]

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.

Solution 5:[5]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 icktoofay
Solution 2
Solution 3
Solution 4 Atario
Solution 5 Quality Catalyst