c-sharp

C# - Get Last N characters from a string

A simple C# extension method which use Substring to get the last N characters in a string.

Abhith Rajan
Abhith RajanSeptember 22, 2019 · 1 min read · Last Updated:

In C#, Substring method is used to retrieve (as the name suggests) substring from a string. The same we can use to get the last ‘N’ characters of a string.

String.Substring Method

As described in String.Substring Method (System) | Microsoft Docs, Substring method has two overloads,

OverloadDescription
Substring(Int32)Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.
Substring(Int32, Int32)Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

With the starting position only overload, we can do.

mystring.Substring(mystring.Length - N);

But the above code will fail in case mystring length is lower than the ‘N’. So considering that case, lets have an extension method,

public static string GetLast(this string source, int numberOfChars)
{
    if(numberOfChars >= source.Length)
      return source;
    return source.Substring(source.Length - numberOfChars);
}

And you can use the above like,

mystring.GetLast(5)

This extension method is now part of the Code.Library Nuget package.

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Abhith Rajan

Written byAbhith Rajan
Abhith Rajan is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related SnippetsView All

Related ArticlesView All

Related VideosView All

C# Project Management in VS Code [Pt 3] | C# and .NET Development in VS Code for Beginners

Installing VS Code and C# Dev Kit [Pt 2] | C# and .NET Development in VS Code for Beginners

What is VS Code and C# Dev Kit? [Pt 1] | C# and .NET Development in VS Code for Beginners