在文章《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),關注公眾號在后臺回復 "新特性" 可獲取更多,轉載請原樣保留本信息。