0

I made a string into .trim(). I wanted to try and reverse it, but I can't seem to do it.

For example,

String a = "    apple     ";

I did, a = a.trim(); such that:

assert(a == "apple");

I want to be able to get back to the original padded text.

assert( a == "    apple     ");
Adam Kipnis
  • 7,448
  • 10
  • 22
  • 37
  • 3
    If you trim it the spaces are gone. If you want to know what it was before, then you should not overwrite it. I'm not sure what the problem is here. – Ivar Apr 21 '18 at 15:34

2 Answers2

3

You cant unless you store the original string and go back to it.

String original = "    apple   ";
String backup = original;
string original = original.trim();
System.out.println(original); //this will show trimmed text
original = backup;
System.out.println(original); //this will show the original untrimmed text.
0

You can't "get them back", but you can record them before you trim them.

You can find the index of the first non-removed character in the string as follows, based on the Javadoc:

int k = 0;
while (k < string.length() && string.charAt(k) <= 0x20) {
  ++k;
}

Now, the leading whitespace is the string string.substring(0, k).

You can do similarly to find the last non-removed character index (call it m); then the trailing whitespace is given by string.substring(m+1).

And now that you've done this, there's no point in using trim(): string.substring(k, m+1) is your trimmed string (provided you have taken care of the "everything in the string is whitespace" case).

Andy Turner
  • 122,430
  • 10
  • 138
  • 216