I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA"
, how can we concatenate it with n times the char '_'
,knowing that the '_'
has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA"
, the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1: As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
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';
}
}
4 Answers 4
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder
instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
-
1Thank you for that. I misread the question initially. It's fixed now.CraigR8806– CraigR880612/21/2016 18:43:58Commented Dec 21, 2016 at 18:43
-
I'm not sure why you are going back and forth, but "_AAAA_AAAA_AAAA" is not what is wanted.OneCricketeer– OneCricketeer12/21/2016 18:48:21Commented Dec 21, 2016 at 18:48
-
3StringBuilder is the best way if you don’t know the size of the final string, because it can alloc memory as it is needed. If you do know the size of the final string, no need to create a complex object to do simple char array filling.Sxilderik– Sxilderik12/21/2016 18:50:42Commented Dec 21, 2016 at 18:50
-
1@CraigR8806 Yes, but it is still slower than filling a
char
arrayOneCricketeer– OneCricketeer12/21/2016 18:54:05Commented Dec 21, 2016 at 18:54 -
1If you are set to use a StringBuilder object to do what a simple char array processing could do, at least you could gain some cycles by using
sb.append('_')
instead ofsb.append("_")
. Using a string to hold a single char is always a performance loss.Sxilderik– Sxilderik12/22/2016 16:07:39Commented Dec 22, 2016 at 16:07
Go to char array, alloting the right size, fill the array, and sum it up back into a string. Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
-
4this is much faster than using a StringBuilderSxilderik– Sxilderik12/21/2016 18:44:44Commented Dec 21, 2016 at 18:44
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
-
Nice use of
Arrays.fill
, thanks for the pointer. On the other hand,a.concat(b)
is faster thana + b
(noStringBuilder
involved) (but don’t doa.concat(b).concat(c)
!).Sxilderik– Sxilderik12/23/2016 08:30:01Commented Dec 23, 2016 at 8:30
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW: Actual answer to the question is in the code of that repeat method.
- when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.
-
Not sure if the overhead of a whole library is needed.
new StringBuilder(new String(new char[n]).replace("0円", "_")).append("AAAAA").toString()
OneCricketeer– OneCricketeer12/21/2016 19:03:56Commented Dec 21, 2016 at 19:03 -
It is about preferences. StringUtils has a lot of useful methods. And are you sure usage of RegEx in replace method will be faster than simple StringBuilder append in the loop?Vadim– Vadim12/21/2016 19:10:07Commented Dec 21, 2016 at 19:10
-
Not super sure, but it just doesn't require a library to essentially do the same thing.OneCricketeer– OneCricketeer12/21/2016 19:15:58Commented Dec 21, 2016 at 19:15
-
In general it depends on nature of application - if it is stand alone simple application, then yes it is better to do not involve libraries. if it is server side app, then who cares about one more jar (usually already there before)?Vadim– Vadim12/21/2016 19:18:32Commented Dec 21, 2016 at 19:18
-
1BTW: StringBuilder solution from @CraigR8806 is the simple and best.Vadim– Vadim12/21/2016 19:20:23Commented Dec 21, 2016 at 19:20
"___"
in a separate step and then do"___" + "AAAA"
?str = "_" + str
is definitely not efficient if you always start withstr = "AAAAA"
. You can build"___"
in one line. stackoverflow.com/a/16812721/2308683 Then you just makethatString + str
str
into the concatenation repeatedly