c-sharp

C# - Get Last N characters from a string

by Abhith RajanSeptember 22, 2019 · 2 min read · Last Updated:
Share this

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.

1mystring.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,

1public static string GetLast(this string source, int numberOfChars)
2{
3 if(numberOfChars >= source.Length)
4 return source;
5 return source.Substring(source.Length - numberOfChars);
6}

And you can use the above like,

1mystring.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 by Abhith Rajan Buy me a coffee
Abhith Rajan is an aspiring software engineer with more than 6 years of experience and proven successful track record of delivering technology-based products and services.