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).