classlib: add stripLeading and stripTrailing methods to String class (#707)

The stripLeading and stripTrailing methods were added in Java 11 to the String class.

Based on the implementation of the existing strip method in TeaVM this commit adds the stripLeading() and stripTrailing() methods (and tests) to the String class in the class library.
This commit is contained in:
Jasper Siepkes 2023-06-06 10:09:25 +02:00 committed by GitHub
parent db69f8ec58
commit 7104edb592
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -487,6 +487,22 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
return substring(lower, upper + 1);
}
public TString stripLeading() {
var lower = 0;
while (lower < length() && Character.isWhitespace(charAt(lower))) {
++lower;
}
return substring(lower, length());
}
public TString stripTrailing() {
var upper = length() - 1;
while (0 <= upper && Character.isWhitespace(charAt(upper))) {
--upper;
}
return substring(0, upper + 1);
}
@Override
public String toString() {
return (String) (Object) this;

View File

@ -209,6 +209,26 @@ public class StringTest {
assertEquals("ab", "\t\n \u2008ab\r\f".strip());
}
@Test
public void stripLeadingWorks() {
assertEquals("ab ", " ab ".stripLeading());
assertEquals("ab ", "ab ".stripLeading());
assertEquals("ab", "ab".stripLeading());
assertEquals("a b", "a b".stripLeading());
assertEquals("", " \t".stripLeading());
assertEquals("ab", "\t\n \u2008\r\fab".stripLeading());
}
@Test
public void stripTrailingWorks() {
assertEquals(" ab", " ab ".stripTrailing());
assertEquals(" ab", " ab".stripTrailing());
assertEquals("ab", "ab".stripTrailing());
assertEquals("a b", "a b".stripTrailing());
assertEquals("", " \t".stripTrailing());
assertEquals("ab", "ab\t\n \u2008\r\f".stripTrailing());
}
@Test
public void convertedToCharArray() {
char[] array = "123".toCharArray();