Java 9 中新增到 String 類的有哪些新方法?


String 是 Java 中的不可變類,有兩種新方法被新增到Java 9中的 String 類中。這些方法是chars()codePoints()。這兩個方法都返回IntStream 物件。

1) chars()

String 類的chars()方法返回此序列中零擴充套件 char 值的 int 流。

語法

public IntStream chars()

示例

import java.util.stream.IntStream;

public class StringCharsMethodTest {
   public static void main(String args[]) {
      String str = "Welcome to TutorialsPoint";
      IntStream intStream = str.chars();
      intStream.forEach(x -> System.out.printf("-%s", (char)x));
   }
}

輸出

-W-e-l-c-o-m-e- -t-o- -T-u-t-o-r-i-a-l-s-P-o-i-n-t


2) codePoints()

codePoints()方法可以返回此序列中的程式碼點值流。

語法

public IntStream codePoints()

示例

import java.util.stream.IntStream;

public class StringCodePointsMethodTest {
   public static void main(String args[]) {
      String str = "Welcome to Tutorix";
      IntStream intStream = str.codePoints();
      intStream.forEach(x -> System.out.print(new StringBuilder().appendCodePoint(x)));
   }
}

輸出

Welcome to Tutorix

更新於: 17-Mar-2020

172 次瀏覽

開啟您的 職業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.