Coder Perfect

In C#, how do I extract the last four characters from a string?


Let’s say I have a string:


I’m looking for the string’s last four letters, which are “d124.” SubString is an option, but it requires a few lines of code, including naming a variable.

Is it possible to get this outcome in C# with just one expression?

Asked by KentZhou

Solution #1

mystring.Substring(Math.Max(0, mystring.Length - 4)); //how many lines is this?

If you’re certain your string is at least four inches long, it’s even shorter:

mystring.Substring(mystring.Length - 4);

Answered by Armen Tsirunyan

Solution #2

You can use an extension method:

public static class StringExtension
    public static string GetLast(this string source, int tail_length)
       if(tail_length >= source.Length)
          return source;
       return source.Substring(source.Length - tail_length);

And then call:

string mystring = "34234234d124";
string res = mystring.GetLast(4);

Answered by Stecya

Solution #3

All you need to do now is…

String result = mystring.Substring(mystring.Length - 4);

Answered by thestar

Solution #4

C# 8.0 eventually makes this simple in 2020:

> "C# 8.0 finally makes this easy"[^4..]

See Indices and ranges for more information on how to slice arrays.

Answered by Colonel Panic

Solution #5

So, I realize this is an old article, but why are we recreating code that the framework already provides?

I recommend that you include a reference to the framework DLL “Microsoft.VisualBasic” in your code.

using Microsoft.VisualBasic;

string value = Strings.Right("34234234d124", 4);

Answered by RJ Programmer

Post is based on