Java 11 已釋出,String 還能這樣玩!
阿新 • • 發佈:2018-12-12
在文章《Java 11 正式釋出,這 8 個逆天新特性教你寫出更牛逼的程式碼》中,我有介紹到 Java 11 的八個新特性,其中關於 String 加強部分,我覺得有點意思,這裡單獨再拉出來講。
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技術棧(id:javastack),關注公眾號在後臺回覆 "新特性" 可獲取更多,轉載請原樣保留本資訊。