Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last 3 characters of string

Tags:

c#

How can I get only the last 3 character out from a given string?

Example input: AM0122200204

Expected result: 204

like image 962
calvin ern Avatar asked Feb 29 '16 03:02

calvin ern


People also ask

How do I get the last 3 characters of a string?

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.

How do I get the last 5 characters of a string?

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.


4 Answers

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

like image 126
Hari Prasad Avatar answered Oct 01 '22 01:10

Hari Prasad


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.

like image 40
Ian Avatar answered Oct 01 '22 03:10

Ian


From C# 8 Indices and ranges

Last 3 digits of "AM0122200204" string:

"AM0122200204"[^3..]
like image 22
Visual Sharp Avatar answered Oct 01 '22 03:10

Visual Sharp


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)
like image 39
Lemon Sky Avatar answered Oct 01 '22 01:10

Lemon Sky