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';
}
}
xmen-5
  • 1,806
  • 1
  • 23
  • 44
  • 1
    Why can't you build `"___"` in a separate step and **then** do `"___" + "AAAA"`? – OneCricketeer Dec 21 '16 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 "_". – xmen-5 Dec 21 '16 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. http://stackoverflow.com/a/16812721/2308683 Then you just make `thatString + str` – OneCricketeer Dec 21 '16 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 . – xmen-5 Dec 21 '16 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 – OneCricketeer Dec 21 '16 at 18:52
  • @cricket_007 firstly i thank you for your help.for your question as suggested by StackOverflow I tried To put a simple example that will be easily readible and that looks like My problem. – xmen-5 Dec 21 '16 at 19:28
  • No worries. You don't need `str = new StringBuilder("AAAAA")`, by the way, you can just have `space.append("AAAAA");` at the end – OneCricketeer Dec 21 '16 at 19:32

4 Answers4

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);
}
Sxilderik
  • 796
  • 6
  • 20
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();
CraigR8806
  • 1,584
  • 13
  • 21
  • 1
    Thank you for that. I misread the question initially. It's fixed now. – CraigR8806 Dec 21 '16 at 18:43
  • I'm not sure why you are going back and forth, but "_AAAA_AAAA_AAAA" is not what is wanted. – OneCricketeer Dec 21 '16 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. – Sxilderik Dec 21 '16 at 18:50
  • @Sxilderik [check this out][1]. It shows that `StringBuilder` is much faster at concatenating Strings [1]: http://www.java67.com/2015/05/4-ways-to-concatenate-strings-in-java.html Hmm I guess I don't know how to properly set links in comments – CraigR8806 Dec 21 '16 at 18:53
  • 1
    @CraigR8806 Yes, but it is still slower than filling a `char` array – OneCricketeer Dec 21 '16 at 18:54
  • @CraigR8806 your solution is more realistic and it's the same idea that cricket_007 showed before, i will edit my question to show the part that i missed to put, thanks. – xmen-5 Dec 21 '16 at 19:06
  • 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. – Sxilderik Dec 22 '16 at 16:07
  • @zakzak puzzles me why you did not pick the fastest way to concatenate strings when you specifically asked for it (_Best way to concatenate Strings in java(Time efficiency)_), but ok, no problem :) – Sxilderik Dec 22 '16 at 18:57
  • @Sxilderik hello , thank you for your help , i gave you a vote.the reason is that i prefer something easy than complicated solution. – xmen-5 Dec 22 '16 at 22:51
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.

stdunbar
  • 16,263
  • 11
  • 31
  • 53
  • 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)` !). – Sxilderik Dec 23 '16 at 08: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.
Vadim
  • 4,027
  • 2
  • 10
  • 26
  • Not sure if the overhead of a whole library is needed. `new StringBuilder(new String(new char[n]).replace("\0", "_")).append("AAAAA").toString()` – OneCricketeer Dec 21 '16 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 Dec 21 '16 at 19:10
  • Not super sure, but it just doesn't require a library to essentially do the same thing. – OneCricketeer Dec 21 '16 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 Dec 21 '16 at 19:18
  • 1
    BTW: StringBuilder solution from @CraigR8806 is the simple and best. – Vadim Dec 21 '16 at 19:20