EN
C# / .NET - get last character from string
0
points
In this article, we would like to show you how to get the last character from a string in C# / .NET.
Quick solution:
string text = "1234";
string lastCharacter = text.Substring(text.Length - 1);
Console.WriteLine(lastCharacter); // 4
Practical example
The below example shows how to use Substring()
method to get the last character from the text
string.
using System;
public class StringUtils
{
public static string getLastCharacters(string text, int charactersCount)
{
int length = text.Length;
int offset = Math.Max(0, length - charactersCount);
return text.Substring(offset);
}
public static void Main(string[] args)
{
Console.WriteLine( getLastCharacters( "1234", 1) ); // 4
Console.WriteLine( getLastCharacters( "123", 1) ); // 3
Console.WriteLine( getLastCharacters( "12", 1) ); // 2
Console.WriteLine( getLastCharacters( "1", 1) ); // 1
Console.WriteLine( getLastCharacters( "", 1) ); //
}
}
Output:
4
3
2
1