EN
C# / .NET - remove last character from string
0 points
In this article, we would like to show you how to remove the last character from the string in C# / .NET.
Quick solution:
xxxxxxxxxx
1
string text = "ABCDE";
2
3
string result = text[..^1];
4
Console.WriteLine(result); // ABC
In this example, we use String Substring()
method to create a new result
substring from the text
string without the last character.
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 - 1);
10
Console.WriteLine(result); // ABCD
11
}
12
}
Output:
xxxxxxxxxx
1
ABCD
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[..^1]; // text[Range.EndAt(new Index(1, fromEnd: true))]
10
Console.WriteLine(result); // ABCD
11
}
12
}
Output:
xxxxxxxxxx
1
ABCD
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 character
10
string result = text.Remove(text.Length - 1);
11
12
Console.WriteLine(result);
13
}
14
}
Output:
xxxxxxxxxx
1
ABCD