Java 11 String 字符串新增 API 教程
String 字符串这个类相信是大家用过的最多的类。随着 java 11 的更新,Oracle 对 String 类终于做了更新。为什么说终于做了更新呢?因为自从 java 6 之后,String 类再也没被更新过。那么这次更新了哪些内容呢?阅读本文,我们一起来看看具体做了哪些更新吧!
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
参考资料
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/04/21 06:17