Java 11, added various new methods in java.lang.String . Let's see each one of them with examples.
Stripping white spaces
Following new methods have been added to remove white spaces:
public String strip()
public String stripLeading()
public String stripTrailing()
Example:
package com.logicbig.example;
public class StringStripExample {
public static void main(String[] args) {
String s = " test string ";
System.out.printf("'%s'%n", s);
String striped = s.strip();
System.out.printf("strip():%n '%s'%n", striped);
striped = s.stripLeading();
System.out.printf("stripLeading():%n '%s'%n", striped);
striped = s.stripTrailing();
System.out.printf("stripTrailing():%n '%s'%n", striped);
}
}
' test string ' strip(): 'test string' stripLeading(): 'test string ' stripTrailing(): ' test string'
strip() vs trim()
strip() is Unicode whitespace aware, whereas the existing method trim() removes any space which is less than or equal to (\u0020).
Following example uses medium mathematical space \u205F, (list of whitespace unicodes)
public class StringStripVsTrimExample {
public static void main(String[] args) {
String s = "test string\u205F";
String striped = s.strip();
System.out.printf("'%s'%n", striped);
String trimmed = s.trim();
System.out.printf("'%s'%n", trimmed);
}
}
'test string'
'test stringā'
See also JDK-8200378.
Blank strings
public boolean isBlank()
This method returns true if the string is empty or contains only white space codepoints, otherwise false. The existing method isEmpty() returns true if length() is 0.
public class StringIsBlankExample {
public static void main(String[] args) {
String s = " ";
//old isEmpty() method
boolean empty = s.isEmpty();
System.out.println(empty);
//new isBlank()
boolean blank = s.isBlank();
System.out.println(blank);
}
} false true
Streaming lines
public Stream<String> lines()
public class StringLinesExample {
public static void main(String[] args) {
String s = "jujube\nsatsuma\nguava";
s.lines()
.forEach(System.out::println);
}
} jujube satsuma guava
Repeating
public String repeat(int count)
This method returns a string whose value is repeated 'count' times
public class StringRepeatExample {
public static void main(String[] args) {
String s = "-";
String newString = s.repeat(10);
System.out.println(newString);
}
} ----------
Example ProjectDependencies and Technologies Used: |