esq619
esq619

Reputation: 641

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#?

Upvotes: 61

Views: 150738

Answers (7)

tleb
tleb

Reputation: 4596

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. Checking the last character therefore looks like:

string str = "foo";
bool ends_with_o = str.Length != 0 && str[^1] == 'o';

Without a length check, this code fails at runtime if str == "":

Unhandled exception. System.IndexOutOfRangeException: Index was 
outside the bounds of the array.
   at System.String.get_Chars(Int32 index)
   ...

Upvotes: 14

Unicorno Marley
Unicorno Marley

Reputation: 1884

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:

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

Upvotes: 115

BigChief
BigChief

Reputation: 1515

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}");
}

Upvotes: 4

icktoofay
icktoofay

Reputation: 129011

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]

Upvotes: 28

Quality Catalyst
Quality Catalyst

Reputation: 6795

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)

Upvotes: 2

Atario
Atario

Reputation: 1390

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.

Upvotes: 0

Parimal Raj
Parimal Raj

Reputation: 20575

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
}

Upvotes: 14

Related Questions