String.join()vs其他字符串连接操作

编程入门 行业动态 更新时间:2024-10-27 01:31:48
本文介绍了String.join()vs其他字符串连接操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经快速阅读了Java8 String api 文档。

I have quickly read over the Java8 String api documentation.

现在我对串联/连接字符串的String.join()方法不感兴趣。

Now I am little curious about String.join() method to concat/join strings.

这种示例帮助我更好地理解:

This kind of example has helped me to understand better, though:

//Old way: String str1 = "John"; String str2 = "Doe"; String result = str1 + " " +str2; //or by using str1.concat(str2); //New way: String result = String.join(" ", str1, str2);

但是,我不明白应该使用哪一个。这两个过程之间是否有任何表现或其他差异。

Still, I don't understand which one should I use. Is there any performance or other differences between these two processes.

任何帮助都将不胜感激。

Any help would be greatly appreciated.

推荐答案

String.join 依赖于类 StringJoiner 本身依赖内部 StringBuilder 来构建连接的字符串。

String.join relies on the class StringJoiner which itself relies on an internal StringBuilder to build the joined string.

因此,性能方面与使用 StringBuilder 并附加到它相同,或使用 + 链(现在编译器将其转换为 StringBuilder 操作)。

So performance-wise it's much the same as using a StringBuilder and appending to it, or using a chain of + (which nowadays are converted to StringBuilder operations by the compiler).

但 String.join 的重要性不是 + 或 String.concat ,但是作为 String.split 操作的反向操作。在这种情况下更有意义 - 当你有一堆字符串想要使用分隔符连接在一起时 - 而不是替换 concat 。

But the significance of String.join is not as a general replacement for + or String.concat, but in being the "reverse operation" of a String.split operation. It makes more sense in that context - when you have a bunch of strings that you want to join together using a delimiter - than as a replacement for concat.

即构建类似a / b / c / d或的输出(a + b + c + d)当你有 a , b , c 和 d , String.join 或者 StringJoiner 会使操作清晰可读。

That is, to build an output like "a/b/c/d" or "(a+b+c+d)" when you have a,b,c and d in an array or a list, String.join or a StringJoiner would make the operation clear and readable.

更多推荐

String.join()vs其他字符串连接操作

本文发布于:2023-11-04 12:32:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557948.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   操作   String   join

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!