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:
xxxxxxxxxx
1
string text = "ABCDE";
2
3
int n = 3;
4
string result = text[..^n];
5
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 n
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
int n = 3;
10
string result = text.Substring(0, text.Length - n);
11
Console.WriteLine(result); // AB
12
}
13
}
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
int n = 3;
10
string result = text[..^n]; // text[Range.EndAt(new Index(n, fromEnd: true))]
11
Console.WriteLine(result); // AB
12
}
13
}
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 n characters
10
int n = 3;
11
string result = text.Remove(text.Length - n);
12
13
Console.WriteLine(result);
14
}
15
}
Output:
xxxxxxxxxx
1
AB