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#

From C# 8 Indices and ranges

Last 3 digits of "AM0122200204" string:

"AM0122200204"[^3..]

Solution 4 - C#

With the introduction of Spans 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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questioncalvin ernView Question on Stackoverflow
Solution 1 - C#Hari PrasadView Answer on Stackoverflow
Solution 2 - C#IanView Answer on Stackoverflow
Solution 3 - C#Visual SharpView Answer on Stackoverflow
Solution 4 - C#Lemon SkyView Answer on Stackoverflow
Solution 5 - C#Юрий ВойнаView Answer on Stackoverflow