EN
C# / .NET - remove last 2 characters from string
0
points
In this article, we would like to show you how to remove the last 2 characters from the string in C# / .NET.
Quick solution:
string text = "ABCDE";
string result = text[..^2];
Console.WriteLine(result); // ABC
Â
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 2
 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";
string result = text.Substring(0, text.Length - 2);
Console.WriteLine(result); // ABC
}
}
Output:
ABC
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";
string result = text[..^2]; // text[Range.EndAt(new Index(2, fromEnd: true))]
Console.WriteLine(result); // ABC
}
}
Output:
ABC
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 2 characters
string result = text.Remove(text.Length - 2);
Console.WriteLine(result);
}
}
Output:
ABC