EN
C# / .NET - get last 3 characters of string
0 points
In this article, we would like to show you how to get the last 3 characters from a string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
string text = "1234";
2
string lastCharacters = text.Substring(text.Length - 3);
3
4
Console.WriteLine(lastCharacters); // 234
The below example shows how to use Substring()
method to get the last 3
characters from the text
string.
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static string getLastCharacters(string text, int charactersCount)
6
{
7
int length = text.Length;
8
int offset = Math.Max(0, length - charactersCount);
9
return text.Substring(offset);
10
}
11
12
public static void Main(string[] args)
13
{
14
Console.WriteLine( getLastCharacters( "1234", 3) ); // 234
15
Console.WriteLine( getLastCharacters( "123", 3) ); // 123
16
Console.WriteLine( getLastCharacters( "12", 3) ); // 12
17
Console.WriteLine( getLastCharacters( "1", 3) ); // 1
18
Console.WriteLine( getLastCharacters( "", 3) ); //
19
}
20
}
Output:
xxxxxxxxxx
1
234
2
123
3
12
4
1
5