2

Is there any equivalent to String.strip() in android, except trim()?

My development environments are Java11, minSdk24, targetSdk31 and compileSdk31. Is that possible to make String.strip() available if I upgrade one of them?

Master Qiao
  • 301
  • 2
  • 10
  • Would e.g. `String stripped = test.replaceAll("(?:^\\p{Z}+)|(?:\\p{Z}+$)", "");` work for you? Not very nice, but it is a one-liner at least. "Stolen" from [here](https://stackoverflow.com/a/1822790/589259)... – Maarten Bodewes Jan 15 '22 at 03:12
  • Don't use regex, performance on that will be orders of magnitude slower. Not to mention regexes are basically non maintainable and not understandable a day after you write them. In general if there's a regex and a non-regex solution, use the non-regex. – Gabe Sechan Jan 15 '22 at 03:15

1 Answers1

1

You can try upgrading your project to use Java 11, which has the function. Or write it yourself, its trivial.

public static String strip(String value) {
    int firstChar = 0;
    while (firstChar < value.length() && Character.isWhitespace(value.charAt(firstChar))) {
        firstChar++;
    }
    int lastChar = value.length() - 1;
    while (lastChar > firstChar && Character.isWhitespace(value.charAt(lastChar))) {
        lastChar--;
    }
    return value.substring(firstChar, lastChar + 1);
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • 1
    No, if lastChar==firstChar, that means there's 1 value character in the string. Imagine the string "a ". You'd end with firstChar =0, lastChar = 0. And you'd want to return "a". firstChar > lastChar means no non-whitespace characters were found. But feel free to write an actual test case and double check me, I just coded it ad hoc, I didn't actually write a test suite. – Gabe Sechan Jan 15 '22 at 03:24
  • 1
    I tested some cases and it works good, thanks – Master Qiao Jan 15 '22 at 04:18