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:
xxxxxxxxxx
1
string text = "1234";
2
string lastCharacter = text.Substring(text.Length - 1);
3
4
Console.WriteLine(lastCharacter); // 4
The below example shows how to use Substring()
method to get the last character from the text
string.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
6
public static string getLastCharacters(string text, int charactersCount)
7
{
8
int length = text.Length;
9
int offset = Math.Max(0, length - charactersCount);
10
return text.Substring(offset);
11
}
12
13
public static void Main(string[] args)
14
{
15
Console.WriteLine( getLastCharacters( "1234", 1) ); // 4
16
Console.WriteLine( getLastCharacters( "123", 1) ); // 3
17
Console.WriteLine( getLastCharacters( "12", 1) ); // 2
18
Console.WriteLine( getLastCharacters( "1", 1) ); // 1
19
Console.WriteLine( getLastCharacters( "", 1) ); //
20
}
21
}
Output:
xxxxxxxxxx
1
4
2
3
3
2
4
1
5