String居然還能這樣玩!
阿新 • • 發佈:2018-12-12
Java 11 增加了一系列的字串處理方法,如以下所示。
// 判斷字串是否為空白 " ".isBlank(); // true // 去除首尾空格 " Javastack ".strip(); // "Javastack" // 去除尾部空格 " Javastack ".stripTrailing(); // " Javastack" // 去除首部空格 " Javastack ".stripLeading(); // "Javastack " // 複製字串 "Java".repeat(3); // "JavaJavaJava" // 行數統計 "A\nB\nC".lines().count(); // 3
最有意思的是 repeat
和 lines
方法了,來看下還能怎麼玩!
repeat
repeat 方法的作用就是重複一個字串 N 遍,可以用來代替工具類:org.apache.commons.lang3.StringUtils#repeat(java.lang.String, int)
,來看下 repeat
的原始碼。
public String repeat(int count) { if (count < 0) { throw new IllegalArgumentException("count is negative: " + count); } if (count == 1) { return this; } final int len = value.length; if (len == 0 || count == 0) { return ""; } if (len == 1) { final byte[] single = new byte[count]; Arrays.fill(single, value[0]); return new String(single, coder); } if (Integer.MAX_VALUE / count < len) { throw new OutOfMemoryError("Repeating " + len + " bytes String " + count + " times will produce a String exceeding maximum size."); } final int limit = len * count; final byte[] multiple = new byte[limit]; System.arraycopy(value, 0, multiple, 0, len); int copied = len; for (; copied < limit - copied; copied <<= 1) { System.arraycopy(multiple, 0, multiple, copied, copied); } System.arraycopy(multiple, 0, multiple, copied, limit - copied); return new String(multiple, coder); }
來看下更多的用法。
String str = "Java";
// 小於0:java.lang.IllegalArgumentException
System.out.println(str.repeat(-2));
// 等於0:空白串("")
System.out.println(str.repeat(0));
// JavaJavaJava
System.out.println(str.repeat(3));
// java.lang.OutOfMemoryError
System.out.println(str.repeat(Integer.MAX_VALUE));
所以說 repeat 並不是可以無限增長的,有使用限制的,達到一定量就會報記憶體溢位異常。
lines
public Stream<String> lines() {
return isLatin1() ? StringLatin1.lines(value)
: StringUTF16.lines(value);
}
lines 方法返回一個字串 Stream, 可以識別 \n
和 \r
換行符換行。
// 4
System.out.println("A\nB\nC\rD".lines().count());
是不是很好?在將來肯定有武之地!如批量讀取檔案內容到一個 Stream 中,就能很好的識別行結束符了。
我有一個微信公眾號,經常會分享一些Java技術相關的乾貨;如果你喜歡我的分享,可以用微信搜尋“Java團長”或者“javatuanzhang”關注。