How to check the last character of a string in C#
In this tutorial, we are going to learn about how to check the last character of a string in C#.
Consider, we have the following string:
string str = "audi";
Now, we need to check if the last character of a above string is character i
or not.
Using EndsWith() method
To check the last character of a string, we can use the built-in EndsWith()
method in C#.
The endsWith()
returns true if a strings ends with specificed character else it returns false.
Here is an example:
string str = "audi";
if(str.EndsWith("i")){
Console.WriteLine("Last character is matched");
}else{
Console.WriteLine("Last character is not matched");
}
Output:
"Last character is matched"
Similarly, you can also check the last character of a string in C# like this:
string str = "audi";
if(str[str.Length()-1] == 'i'){
Console.WriteLine("Last character is matched");
}else{
Console.WriteLine("Last character is not matched");
}