Extract rightmost `n` characters from a string in C#
This post will discuss how to extract rightmost n
characters from a string in C#.
For example, if the string is ABC1234
and n = 4
, the solution should give substring 1234
.
Here’s a utility method that shows how to implement this with the String.Substring() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; public static class Extensions { public static string Right(this string str, int n) { return str.Substring(str.Length - n); } } public class Example { public static void Main() { string str = "Techie Delight"; int n = 7; string substr = str.Right(n); Console.WriteLine(substr); } } /* Output: Delight */ |
The above approach will throw an ArgumentOutOfRangeException
when the string’s length is less than the total number of characters required. The following code example demonstrates how to handle this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; public static class Extensions { public static string Right(this string str, int n) { if (n > str.Length) { return str; } return str.Substring(str.Length - n); } } public class Example { public static void Main() { string str = "Techie Delight"; int n = 7; string substr = str.Right(n); Console.WriteLine(substr); } } /* Output: Delight */ |
Here’s another alternative syntax that handles the case when string length is less than the total number of characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; public static class Extensions { public static string Right(this string str, int n) { return str.Substring(str.Length < n ? 0 : (str.Length - n)); } } public class Example { public static void Main() { string str = "Techie Delight"; int n = 7; string substr = str.Right(n); Console.WriteLine(substr); } } /* Output: Delight */ |
That’s all about extracting rightmost n
characters from a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)