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:
xxxxxxxxxx
1
string text = "ABCDE";
2
3
string result = text[..^3];
4
Console.WriteLine(result); // AB
In this example, we use String Substring()
method to create a new result
substring from the text
string without the last 3
characters.
Syntax:
xxxxxxxxxx
1
Substring (int startIndex, int length);
Note:
If
length
is not given, substring will be done fromstartIndex
to the end of the text.
Practical example:
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string text = "ABCDE";
8
9
string result = text.Substring(0, text.Length - 3);
10
Console.WriteLine(result); // AB
11
}
12
}
Output:
xxxxxxxxxx
1
AB
The range operator ..
is used to make a slice of the collection.
Practical example:
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string text = "ABCDE";
8
9
string result = text[..^3]; // text[Range.EndAt(new Index(3, fromEnd: true))]
10
Console.WriteLine(result); // ABC
11
}
12
}
Output:
xxxxxxxxxx
1
AB
Syntax:
xxxxxxxxxx
1
Remove (int startIndex, int count);
Practical example:
xxxxxxxxxx
1
using System;
2
3
public class StringUtils
4
{
5
public static void Main(string[] args)
6
{
7
string text = "ABCDE";
8
9
// Remove last 3 characters
10
string result = text.Remove(text.Length - 3);
11
12
Console.WriteLine(result);
13
}
14
}
Output:
xxxxxxxxxx
1
AB