This site requires JavaScript, please enable it in your browser!
Greenfoot back
darkmist255
darkmist255 wrote ...

2012/5/28

Removing characters from a string?

darkmist255 darkmist255

2012/5/28

#
I've been doing lots of work with Arrays and Lists today and ran into the problem of trying to remove characters from a string (hit backspace to make string remove last character). I'm thinking maybe I could do something along the lines of "someString.toCharArray()", remove the last data object, then convert it back somehow. Is this along the right line of thinking for how to do this?
SPower SPower

2012/5/28

#
It would work with toCharArray(), this is what you need to do:
char[] array = myString.toCharArray();
char[] newString = new char[myString.length() -1];
for (int i = 0; i < myString.length() -1; i++) {
     newString[i] = array[i];
}
String theNewString = new String(newString);
And now, you've got a new string, with one character less than the original.
Builderboy2005 Builderboy2005

2012/5/28

#
If you are removing the very last character of the string only, you can actually just use the substring() method:
myString = myString.subString(0,myString.length()-2);
danpost danpost

2012/5/28

#
Builderboy2005 wrote...
If you are removing the very last character of the string only, you can actually just use the substring() method:
myString = myString.subString(0,myString.length()-2);
The code given will remove two characters from the end of the string. To remove only one, use:
myString = myString.substring(0, myString.length() - 1);
Also, notice that 'substring' does not contain any uppercase letters.
danpost danpost

2012/5/28

#
For information on basic string manipulation, see here.
Builderboy2005 Builderboy2005

2012/5/28

#
Blarg I checked the documentation when I wrote the post, but I always forget that the first index is inclusive while the second index is exclusive >.<
darkmist255 darkmist255

2012/5/28

#
Ah, the info on string manipulation was very helpful, as with the advice! Although toCharArray would work I'll go the proper way and learn how to manipulate strings properly (seems straightforward upon just reading over it). Very helpful guys, thanks! I'm really getting into data manipulation, arrays, lists, etc.
You need to login to post a reply.