3

I'm trying to remove a character from inside a string, say, 3 spaces from the end. I'm using this to act as typing on a screen in a game in unity, think like a text editor, where you can use the arrow keys to move the cursor inside of the string to remove characters. For example,

"Hello World!"

After pressing left arrow 3 times (I know how to increase/decrease this number obviously, just not where to put the '3'), and then pressing backspace, it should become:

"Hello Wold!"

Currently I am using .Remove(0, text.Length - 1) (Didn't just copy/paste this code so might be a bit off, just memory) to remove characters from the end, but I don't believe that will work for this. Thank you for any help you give!

Jim
  • 2,974
  • 2
  • 19
  • 29
ZachHofmeister
  • 163
  • 1
  • 2
  • 6
  • 1
    http://stackoverflow.com/questions/8098556/remove-last-characters-from-a-string-in-c-an-elegant-way The answer I like best, myself, is the accepted answer here -- you can avoid hardcoding the number. – Michael Armes Oct 28 '16 at 15:15
  • "I don't believe that will work for this" .... did you tried it ? – Jim Oct 28 '16 at 15:51
  • Sorry, wasn't very clear but I did try it, just missed the solution to it. – ZachHofmeister Oct 28 '16 at 17:25

3 Answers3

5

You can use the String.Remove overload which takes the starting point and number of characters to be removed:

string str = "Hello World!";
string resultStr = str.Remove(str.Length - 4, 1);

Make sure to check the string length first.

Habib
  • 219,104
  • 29
  • 407
  • 436
  • Thanks, tried something similar but I got it backwards. And yes, I will have to make sure that it doesn't decrease past the length of the string. – ZachHofmeister Oct 28 '16 at 17:27
1

This seems to be working:

var text = "Hello World!";
var index = 3;
text.Remove(text.Length - index - 1, 1);
TKharaishvili
  • 1,997
  • 1
  • 19
  • 30
0

you could use Substring.

substring(int startIndex, int endIndex)

e.g

String s = substring(0, s.length()-3);//removes the last 3 strings.
Jim
  • 2,974
  • 2
  • 19
  • 29
oziomajnr
  • 1,671
  • 1
  • 15
  • 39