Get The Last Character Of A String In C#

Sameer Saini May 30, 2022
Get The Last Character Of A String In C#

In this blog post, we are going to learn how we can get the last character of a string in C#.

There can be many use cases where this might be necessary.

We will make use of the .Length property and the .Substring() method to get the last character in the string.

 

 

 

 

Get Last Character Of A String Using the .Length Property In C#

In this method, we will use the .Length property on a string to calculate the length of the string and then subtract 1 from the length to use that to get the last character of the string.

 

Example:

namespace ConsoleApp { public class Program { public static void Main() { string sampleString = "Code Like A Dev"; char lastCharacter = sampleString[sampleString.Length - 1]; Console.WriteLine(lastCharacter); } } }

 

Result:

v

 

 

Get Last Character Of A String Using the .Substring() Method In C#

In this method, we will use the .Substring method on a string to calculate the length of the string and then subtract 1 from the length to use that to get the last character of the string.

 

Example:

namespace ConsoleApp { public class Program { public static void Main() { string sampleString = "Code Like A Dev"; string lastCharacter = sampleString.Substring(sampleString.Length - 1); Console.WriteLine(lastCharacter); } } }

 

Result:

v