EN
C# / .NET - remove last n characters from string
0
points
In this article, we would like to show you how to remove the last n characters from the string in C# / .NET.
Quick solution:
string text = "ABCDE";
int n = 3;
string result = text[..^n];
Console.WriteLine(result); // AB
Â
Practical examples
1. Using String Substring()
 method
In this example, we use String Substring()
 method to create a new result
substring from the text
string without the last n
 characters.
Syntax:
Substring (int startIndex, int length);
Note:
If
length
is not given, substring will be done fromstartIndex
to the end of the text.
Practical example:
using System;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABCDE";
int n = 3;
string result = text.Substring(0, text.Length - n);
Console.WriteLine(result); // AB
}
}
Output:
AB
2. Using index from end ^
and range operator ..
The range operator ..
 is used to make a slice of the collection.
Practical example:
using System;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABCDE";
int n = 3;
string result = text[..^n]; // text[Range.EndAt(new Index(n, fromEnd: true))]
Console.WriteLine(result); // AB
}
}
Output:
AB
3. Using String Remove()
method
Syntax:
Remove (int startIndex, int count);
Practical example:
using System;
public class StringUtils
{
public static void Main(string[] args)
{
string text = "ABCDE";
// Remove last n characters
int n = 3;
string result = text.Remove(text.Length - n);
Console.WriteLine(result);
}
}
Output:
AB