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.