[c#] Remove the last three characters from a string

I want to remove last three characters from a string:

string myString = "abcdxxx"; 

Note that the string is dynamic data.

This question is related to c# .net

The answer is


str= str.Remove(str.Length - 3);


myString.Remove(myString.Length-3);

myString = myString.Remove(myString.Length - 3, 3);

I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:

string.Concat("hello".Reverse().Skip(3).Reverse());

output:

"he"

   string myString = "abcdxxx";
   if (myString.Length<3)
      return;
   string newString=myString.Remove(myString.Length - 3, 3);

Probably not exactly what you're looking for since you say it's "dynamic data" but given your example string, this also works:

? "abcdxxx".TrimEnd('x');
"abc"

string test = "abcdxxx";
test = test.Remove(test.Length - 3);
//output : abcd

items.Remove(items.Length - 3)

string.Remove() removes all items from that index to the end. items.length - 3 gets the index 3 chars from the end


The new C# 8.0 range operator can be a great shortcut to achieve this.

Example #1 (to answer the question):

string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd

Example #2 (to show you how awesome range operators are):

string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98

Easy. text = text.remove(text.length - 3). I subtracted 3 because the Remove function removes all items from that index to the end of the string which is text.length. So if I subtract 3 then I get the string with 3 characters removed from it.

You can generalize this to removing a characters from the end of the string, like this:

text = text.remove(text.length - a) 

So what I did was the same logic. The remove function removes all items from its inside to the end of the string which is the length of the text. So if I subtract a from the length of the string that will give me the string with a characters removed.

So it doesn't just work for 3, it works for all positive integers, except if the length of the string is less than or equal to a, in that case it will return a negative number or 0.


myString.Substring(myString.Length - 3, 3)

Here are examples on substring.>>

http://www.dotnetperls.com/substring

Refer those.


Remove the last characters from a string

TXTB_DateofReiumbursement.Text = (gvFinance.SelectedRow.FindControl("lblDate_of_Reimbursement") as Label).Text.Remove(10)

.Text.Remove(10)// used to remove text starting from index 10 to end


You can use String.Remove to delete from a specified position to the end of the string.

myString = myString.Remove(myString.Length - 3);