日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

string 换行符_Java 11 已发布,String 还能这样玩!

發布時間:2025/6/17 106 豆豆
生活随笔 收集整理的這篇文章主要介紹了 string 换行符_Java 11 已发布,String 还能这样玩! 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在文章《Java 11 正式發布,這 8 個逆天新特性教你寫出更牛逼的代碼》中,我有介紹到 Java 11 的八個新特性,其中關于 String 加強部分,我覺得有點意思,這里單獨再拉出來講。

Java 11 增加了一系列的字符串處理方法,如以下所示。

// 判斷字符串是否為空白 " ".isBlank(); // true// 去除首尾空格 " Javastack ".strip(); // "Javastack"// 去除尾部空格 " Javastack ".stripTrailing(); // " Javastack"// 去除首部空格 " Javastack ".stripLeading(); // "Javastack "// 復制字符串 "Java".repeat(3); // "JavaJavaJava"// 行數統計 "AnBnC".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("AnBnCrD".lines().count());

是不是很好?在將來肯定有武之地!如批量讀取文件內容到一個 Stream 中,就能很好的識別行結束符了。

總結

以上是生活随笔為你收集整理的string 换行符_Java 11 已发布,String 还能这样玩!的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。