gpt4 book ai didi

java - 在java中连接字符串的最佳方法(时间效率)

转载 作者:行者123 更新时间:2023-11-29 09:59:29 24 4
gpt4 key购买 nike

我检查了许多关于在 Java 中连接多个字符串的最佳方法的讨论。

据我所知,Stringbuilder 比 + 运算符更有效。

不幸的是,我的问题有点不同。

给定字符串:"AAAAA",我们如何将它与 n 倍的字符 '_' 连接起来,知道 '_' 必须在字符串“AAAAA”之前

如果 n 等于 3str="AAAAA",结果必须是字符串 "___AAAAA"

String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}

在我的程序中我有一个 Longs String ,所以我必须使用高效的方式。

谢谢

编辑 1:当我阅读一些解决方案时,我发现我只要求一个案例,所以我得出了这个我认为不错的解决方案:

public class Concatenation {

public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}

最佳答案

在 Java 中连接字符串的最佳方法:您不需要...。字符串在 Java 中是不可变的。每次连接时,都会生成一个新对象。请改用 StringBuilder

 StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();

关于java - 在java中连接字符串的最佳方法(时间效率),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41269658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com