169

I want to remove last three characters from a string:

string myString = "abcdxxx"; 

Note that the string is dynamic data.

0

16 Answers 16

315

read last 3 characters from string [Initially asked question]

You can use string.Substring and give it the starting index and it will get the substring starting from given index till end.

myString.Substring(myString.Length-3)

Retrieves a substring from this instance. The substring starts at a specified character position. MSDN

Edit, for updated post

Remove last 3 characters from string [Updated question]

To remove the last three characters from the string you can use string.Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

myString = myString.Substring(0, myString.Length-3);

String.Substring Method (Int32, Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

You can also using String.Remove(Int32) method to remove the last three characters by passing start index as length - 3, it will remove from this point to end of string.

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

String.Remove Method (Int32)

Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted

6
  • 16
    this is so not the answer
    – braks
    Jan 5, 2016 at 2:46
  • 26
    Thanks @braks, the question initially asked was "read last 3 characters from string" This is later edited and I did not know, see the question edit history. Your comment helped me to correct my answer that became wrong after edit of the question.
    – Adil
    Jan 5, 2016 at 4:55
  • 3
    In C#8+, you can do this myString[..^3]
    – Granger
    Sep 16, 2021 at 15:20
  • @Granger, and it helps to note this is useless on C#9 on Framework 4.x
    – WLFree
    Oct 12, 2022 at 4:26
  • @WLFree - The range operators are a language feature, not a framework feature.
    – Granger
    Oct 14, 2022 at 22:36
30
myString = myString.Remove(myString.Length - 3, 3);
1
  • The documentation on String.Remove is confusing. The lead sentence: "Returns a new string in which a specified number of characters from the current string are deleted." This makes one think at first that string.Remove(3) would do the trick (or maybe remove three characters from the start of the string), but then on reading the overload descriptions one realises it doesn't.
    – Stewart
    Oct 7, 2020 at 13:57
19

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"
7
  • 11
    This one is quite "creative", since it doesn't need the string's length, but the reverse operation is probably more expensive.
    – Aleksandar
    Apr 7, 2017 at 9:12
  • 4
    Reversing a string is definitely more expensive than counting its characters. A whole new string needs to be constructed, then the original copied to it, then the original string needs to be garbage collected. Apr 24, 2017 at 16:26
  • @MattGregory strings are immutable: Remove, Substring, any string function generates a new string. Overwriting the original pointer always causes garbage collection. This is still slower though, as Enumerable.Reverse buffers the string into a char[], then buffers into a new char[] that's 3 shorter, and then generates a new string (with internally another char[]). A better approach would be new string("hello".Reverse().Skip(3)), or just writing your own string extension function AllBut(this string in, int i) that uses Substring.
    – Wolfzoon
    Jan 11, 2018 at 10:38
  • 1
    @MattGregory It's not even "counting" a string's characters, a string has its Length stored.
    – Wolfzoon
    Jan 11, 2018 at 10:38
  • 1
    Now we also have .SkipLast(n). No need to reverse anything. "hello".SkipLast(3) gives "he" Feb 20, 2020 at 15:02
16

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
5
  • 2
    Range operators are badass.
    – Arvo Bowen
    Feb 17, 2021 at 21:43
  • 1
    They are badass. I advise caution on overusing them... you can sometimes make code too hard to read by being "too clever". But they are a brilliant way to be concise and get what you want
    – vullnetyy
    Feb 18, 2021 at 23:54
  • 1
    I don't know what you're talking about, these 32 nested range operators in my method look like a beautiful plate of spaghetti.
    – Arvo Bowen
    Feb 19, 2021 at 20:50
  • Hahahaha! Nono it ain’t that bad. One can go much further with them. I am merely advising caution for anyone reading this and getting overly inspired :)
    – vullnetyy
    Feb 20, 2021 at 21:31
  • I agree with @vullnetyy - these shortcuts are really cool but, for example, using a range operator instead of a SubString or Remove makes code substantially less readable.
    – Edwardo
    Jun 30, 2021 at 11:36
12
myString.Remove(myString.Length-3);
1
  • 4
    myString = myString.Remove(myString.Length - 3) that is. Jun 9, 2017 at 20:42
7
string test = "abcdxxx";
test = test.Remove(test.Length - 3);
//output : abcd
6

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

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

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"
0
5

If you're working in C# 8 or later, you can use "ranges":

string myString = "abcdxxx";
string trimmed = myString[..^3]; // "abcd"

More examples:

    string test = "0123456789", s;
    char c;
    c = test[^3]; // '7'
    s = test[0..^3]; // "0123456"
    s = test[..^3]; // "0123456"
    s = test[2..^3]; // "23456"
    s = test[2..7]; // "23456"
    //c = test[^12]; // IndexOutOfRangeException
    //s = test[8..^3]; // ArgumentOutOfRangeException
    s = test[7..^3]; // string.Empty
3

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

3

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.

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

Here are examples on substring.>>

http://www.dotnetperls.com/substring

Refer those.

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

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

1
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

-1

You can call the Remove method and pass the last 3 characters

str.Substring(str.Length-3)

Complete code can be

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.