EN
C# / .NET - get last n characters from string
0 points
In this article, we would like to show you how to get the last n characters from a string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
string text = "1234";
2
int n = 2;
3
string lastCharacters = text.Substring(text.Length - n);
4
5
Console.WriteLine(lastCharacters); // 34
The below example shows how to use Substring()
method to get the last n
characters 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", 3) ); // 234
16
Console.WriteLine( getLastCharacters( "1234", 2) ); // 34
17
Console.WriteLine( getLastCharacters( "12", 2) ); // 12
18
Console.WriteLine( getLastCharacters( "1", 2) ); // 1
19
Console.WriteLine( getLastCharacters( "", 2) ); //
20
}
21
}
Output:
xxxxxxxxxx
1
234
2
34
3
12
4
1
5