3

I want to duplicate a String by a given number separated by ,. For example:

int i=3;
String word = "a"; 
String result = String.duplicate(word, ',', i);

// result is: "a,a,a"

I know there is something like that in Ruby but I'm looking in Java. I wrote some code with a loop and then I removed the last char (which is the ,). I wondered if there is a build-in function.

I did write my own function, I just wanted to know if there is build-in for that..

Nir
  • 2,497
  • 9
  • 42
  • 71

4 Answers4

6

Commons Lang - StringUtils#repeat:

StringUtils.repeat("a", ",", 3);
Pavel Horal
  • 17,782
  • 3
  • 65
  • 89
  • True, but I wrote it before the question was rephrased and the *"lets all write how to concatenate strings" mania* started :). – Pavel Horal Oct 07 '13 at 20:15
1

why not write a method of your own

public String duplicate(String word, String separator, int count) {

  StringBuilder str = new StringBuilder();
  for (int i =0; i < count; i++) {
    str.append(word);
    if (i != count - 1) {
      // append comma only for more than one words
      str.append(separator);
    }
  }

   return str.toString();
}
S4beR
  • 1,872
  • 1
  • 17
  • 33
0

Nothing in native Java to do this (besides actually doing it obviously):

public static void main(String[] args) {
    System.out.println(join("a", ",", 3));
}

public static String join(final String in, final String on, final int num) {
    if (num < 1) {
        throw new IllegalArgumentException();
    }
    final StringBuilder stringBuilder = new StringBuilder(in);
    for (int i = 1; i < num; ++i) {
        stringBuilder.append(on).append(in);
    }
    return stringBuilder.toString();
}

In Guava you could do:

Joiner.on(',').join(Collections.nCopies(3, "a"))
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
0

Here's a log (n) solution:

public static String join(String string, int n){
   StringBuilder sb = new StringBuilder(string);
   StringBuilder out = new StringBuilder();
   sb.append(",");

   for (;n>0;n=n>>1){
        if (n%2==1){
           out.append(sb.toString());
        }
       sb.append(sb);
   }

   out.deleteCharAt(out.length()-1);
   return out.toString();
}
Jason
  • 13,563
  • 15
  • 74
  • 125
  • 1
    This actually does more work than a simple loop. There's not much you can do to make it faster. Only thing that I can come up with is counting amount of space required and preallocating the buffer before filling it – Sami Korhonen Oct 07 '13 at 20:22