1

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';
}
}
asked Dec 21, 2016 at 18:35
7
  • 1
    Why can't you build "___" in a separate step and then do "___" + "AAAA"? Commented Dec 21, 2016 at 18:38
  • @cricket_007 good idea for this case, but in my program i have to deel with the general case.your solution will work only for the case of those "_". Commented Dec 21, 2016 at 18:40
  • Not sure what you mean. But str = "_" + str is definitely not efficient if you always start with str = "AAAAA". You can build "___" in one line. stackoverflow.com/a/16812721/2308683 Then you just make thatString + str Commented Dec 21, 2016 at 18:41
  • @cricket_007 i understood your solution but my program is more complex than the one i puted above.im program sometimes each time i deel with one character, so i have to append the String each time . Commented Dec 21, 2016 at 18:45
  • 2
    If your program is more complex, then why did you provide this simple example? All I'm saying is that the underscores can be pre-filled. You don't need to copy str into the concatenation repeatedly Commented Dec 21, 2016 at 18:52

4 Answers 4

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();
answered Dec 21, 2016 at 18:40
9
  • 1
    Thank you for that. I misread the question initially. It's fixed now. Commented 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. Commented Dec 21, 2016 at 18:48
  • 3
    StringBuilder 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. Commented Dec 21, 2016 at 18:50
  • 1
    @CraigR8806 Yes, but it is still slower than filling a char array Commented Dec 21, 2016 at 18:54
  • 1
    If 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 of sb.append("_"). Using a string to hold a single char is always a performance loss. Commented Dec 22, 2016 at 16:07
4

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);
}
answered Dec 21, 2016 at 18:39
1
  • 4
    this is much faster than using a StringBuilder Commented Dec 21, 2016 at 18:44
1

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.

answered Dec 21, 2016 at 18:51
1
  • Nice use of Arrays.fill, thanks for the pointer. On the other hand, a.concat(b) is faster than a + b (no StringBuilder involved) (but don’t do a.concat(b).concat(c) !). Commented Dec 23, 2016 at 8:30
0

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.
answered Dec 21, 2016 at 18:56
5
  • Not sure if the overhead of a whole library is needed. new StringBuilder(new String(new char[n]).replace("0円", "_")).append("AAAAA").toString() Commented 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? Commented Dec 21, 2016 at 19:10
  • Not super sure, but it just doesn't require a library to essentially do the same thing. Commented 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)? Commented Dec 21, 2016 at 19:18
  • 1
    BTW: StringBuilder solution from @CraigR8806 is the simple and best. Commented Dec 21, 2016 at 19:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.