Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get last 4 characters from string innC#?
Getting the last 4 characters from a string in C# is a common task that can be accomplished using the Substring() method. This method extracts a portion of the string based on the starting position and length specified.
Syntax
Following is the syntax for using Substring() to get the last characters −
string.Substring(startIndex) string.Substring(startIndex, length)
To get the last 4 characters, calculate the starting position as −
str.Substring(str.Length - 4)
Using Substring() Method
The Substring() method extracts characters from a specified starting position to the end of the string. To get the last 4 characters, we start from str.Length - 4 position −
using System;
public class Demo {
public static void Main() {
string str = "Football and Tennis";
string res = str.Substring(str.Length - 4);
Console.WriteLine("Original string: " + str);
Console.WriteLine("Last 4 characters: " + res);
}
}
The output of the above code is −
Original string: Football and Tennis Last 4 characters: nnis
Using Take() Method with LINQ
Another approach is using LINQ's Skip() and Take() methods to get the last characters −
using System;
using System.Linq;
public class Demo {
public static void Main() {
string str = "Programming";
string last4 = new string(str.Skip(str.Length - 4).ToArray());
Console.WriteLine("Original string: " + str);
Console.WriteLine("Last 4 characters: " + last4);
}
}
The output of the above code is −
Original string: Programming Last 4 characters: ming
Handling Edge Cases
When working with strings shorter than 4 characters, it's important to add proper validation to avoid exceptions −
using System;
public class Demo {
public static string GetLast4Characters(string input) {
if (string.IsNullOrEmpty(input)) {
return "";
}
return input.Length >= 4 ? input.Substring(input.Length - 4) : input;
}
public static void Main() {
string[] testStrings = {"Hello World", "C#", "Code", "Programming"};
foreach (string str in testStrings) {
string result = GetLast4Characters(str);
Console.WriteLine($"'{str}' -> Last 4: '{result}'");
}
}
}
The output of the above code is −
'Hello World' -> Last 4: 'orld' 'C#' -> Last 4: 'C#' 'Code' -> Last 4: 'Code' 'Programming' -> Last 4: 'ming'
Conclusion
The Substring() method is the most straightforward way to extract the last 4 characters from a string in C#. Always validate string length to prevent ArgumentOutOfRangeException when working with strings shorter than the desired character count.
