Nir
Nir

Reputation: 2629

Duplicate string in java

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..

Upvotes: 3

Views: 789

Answers (4)

Jason
Jason

Reputation: 13964

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();
}

Upvotes: 0

Boris the Spider
Boris the Spider

Reputation: 61138

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"))

Upvotes: 0

S4beR
S4beR

Reputation: 1847

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();
}

Upvotes: 1

Pavel Horal
Pavel Horal

Reputation: 18194

Commons Lang - StringUtils#repeat:

StringUtils.repeat("a", ",", 3);

Upvotes: 6

Related Questions