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