Java 9 中 String 类添加了哪些新方法?

javaobject oriented programmingprogramming更新于 2025/9/10 13:32:17

String 是 Java 中的不可变类,Java 9 中 String 类添加了两个新方法。这些方法是chars()和codePoints()。这两个方法都返回 IntStream 对象。

1) chars():

String 类的 chars() 方法可以返回一个 int 流,该流对该序列中的 char 值进行零扩展。

语法

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

相关文章


有用资源