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.

commit 9d17c5a · authored · 1 min read

C# - Get Last N characters from a string

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.

local graph · open full graph

"C# - Get Last N characters from a string" is connected to the topics C# and related to 7 other entries. NDepend - The Best-in-class Static Code Analyzer for Dotnet NDepend - The Best-in-class… C# - Convert DateTime to Long and Vice Versa C# - Convert DateTime to Lo… C# - Get Web.Config Connection String in a Class Library C# - Get Web.Config Connect… Using AutoMapper in a .NET Core Class Library Using AutoMapper in a .NET … Check if string is Arabic - C# Check if string is Arabic -… Truncate String Without Word Break Truncate String Without Wor… Mask String Mask String C# #c-sharp C# - Get Last N characters from a…

comments

loading discussion…