Get last 3 characters of string
C#C# Problem Overview
How can I get only the last 3 character out from a given string?
Example input: AM0122200204
Expected result: 204
C# Solutions
Solution 1 - C#
Many ways this can be achieved.
Simple approach should be taking Substring
of an input string.
var result = input.Substring(input.Length - 3);
Another approach using Regular Expression
to extract last 3 characters.
var result = Regex.Match(input,@"(.{3})\s*$");
Working Demo
Solution 2 - C#
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
Solution 3 - C#
Solution 4 - C#
With the introduction of Span
s in C# 7.3 and .NET Core 2.1 we now have an additional way of implementing this task without additional memory allocations. The code would look as follows:
var input = "AM0122200204";
var result = input
.AsSpan()
.Slice(input.Length - 3);
In traditional code, every string manipulation creates a new string on the heap. When doing heavy string-based manipulations like in compilers or parsers, this can quickly become a bottleneck.
In the code above, .AsSpan()
creates a safe, array-like structure pointing to the desired memory region inside the original string. The resulting ReadOnlySpan
is accepted by many method overloads in libraries.
For example, we can parse the last 3 digits using int.Parse
:
int value = int.Parse(result)
Solution 5 - C#
let newString = oldString.slice(-3)