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:
string text = "ABCDE";
string result = text[..^1];
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 character.
Syntax:
Substring (int startIndex, int length);
Note:
If
lengthis not given, substring will be done fromstartIndexto 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 - 1);
Console.WriteLine(result); // ABCD
}
}
Output:
ABCD
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[..^1]; // text[Range.EndAt(new Index(1, fromEnd: true))]
Console.WriteLine(result); // ABCD
}
}
Output:
ABCD
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 character
string result = text.Remove(text.Length - 1);
Console.WriteLine(result);
}
}
Output:
ABCD