Java基础、中级、高级、架构面试资料

Java 11 String 字符串新增 API 教程

JAVA herman 3010浏览 0评论
公告:“业余草”微信公众号提供免费CSDN下载服务(只下Java资源),关注业余草微信公众号,添加作者微信:xttblog2,发送下载链接帮助你免费下载!
本博客日IP超过2000,PV 3000 左右,急需赞助商。
极客时间所有课程通过我的二维码购买后返现24元微信红包,请加博主新的微信号:xttblog2,之前的微信号好友位已满,备注:返现
受密码保护的文章请关注“业余草”公众号,回复关键字“0”获得密码
所有面试题(java、前端、数据库、springboot等)一网打尽,请关注文末小程序
视频教程免费领
腾讯云】1核2G5M轻量应用服务器50元首年,高性价比,助您轻松上云

String 字符串这个类相信是大家用过的最多的类。随着 java 11 的更新,Oracle 对 String 类终于做了更新。为什么说终于做了更新呢?因为自从 java 6 之后,String 类再也没被更新过。那么这次更新了哪些内容呢?阅读本文,我们一起来看看具体做了哪些更新吧!

java 11

repeat() 方法

新增的 repeat() 方法,能够让我们快速的复制多个子字符串。用法和效果如下:

var string = "www.xttblog.com 业余草 ";
var result = string.repeat(2); //www.xttblog.com 业余草 www.xttblog.com 业余草 

根据 repeat() 方法,我们可以得到一个空的字符串。只需把参数 2 改为 0 即可。类似下面的用法:

var string = "www.xttblog.com 业余草 ";
var result = string.repeat(0);
assertThat(result).isEqualTo("");

如果 repeat() 方法的参数是 Integer.MAX_VALUE,那么它也返回一个空字符串。

var string = "www.xttblog.com 业余草 ";
var result = string.repeat(Integer.MAX_VALUE);
assertThat(result).isEqualTo("");

以下是 java 11 String 字符串类 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);
}

可以看到它并不是依赖 StringBuilder 来实现复制字符串的。

isBlank() 方法

java 11 中新增了 isBlank() 方法,从此之后我们再也不需要第三方 jar 包来支持判断是空的还是包含空格了。

var result = " ".isBlank(); // true

strip() 方法

新增的 strip() 方法可以去除首尾空格。

assertThat("  业余 草  ".strip()).isEqualTo("业余 草");

stripLeading() 方法

stripLeading() 方法可以去除头部空格。

assertThat("  业余 草  ". stripLeading()).isEqualTo("业余 草  ");

stripTrailing() 方法

stripTrailing() 方法去除尾部空格。

assertThat("  业余 草  ". stripLeading()).isEqualTo("  业余 草");

看完上面的 3 个 API,你可能要问,它们是不是和 trim() 方法的作用重复了?答案是并不重复。strip 是一种基于 Unicode 识别替代方案。

lines() 方法

使用 lines() 方法,我们可以轻松地将 String 实例拆分为 Stream :

"业余草\nwww.xttblog.com".lines().forEach(System.out::println);

// 业余草
// www.xttblog.com

参考资料

业余草公众号

最后,欢迎关注我的个人微信公众号:业余草(yyucao)!可加作者微信号:xttblog2。备注:“1”,添加博主微信拉你进微信群。备注错误不会同意好友申请。再次感谢您的关注!后续有精彩内容会第一时间发给您!原创文章投稿请发送至532009913@qq.com邮箱。商务合作也可添加作者微信进行联系!

本文原文出处:业余草: » Java 11 String 字符串新增 API 教程