How can I get only the last 3 character out from a given string?
Example input: AM0122200204
Expected result: 204
Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
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
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.
From C# 8 Indices and ranges
Last 3 digits of "AM0122200204" string:
"AM0122200204"[^3..]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With