1

is there a nice way for creating a string initialized with a number of characters given an int (counter) and the character to set. Simply put I would like a method that returns "#,#,#,#,#" when passed 5 and # as parameter.

Any ideas?

3 Answers 3

1

Using the StringUtils utility in the Apache Commons lang library:

String myString = StringUtils.repeat("#", ",", 5);

If you only want the characters (and not the comma separators), it is just:

String myString = StringUtils.repeat("#", 5);
Sign up to request clarification or add additional context in comments.

Comments

1

It's pretty simple to write a method for this:

public static String createPlaceholderString(char placeholder, int count) {
    StringBuilder builder = new StringBuilder(count * 2 - 1);
    for (int i = 0; i < count; i++) {
        if (i!= 0) {
            builder.append(',');
        }
        builder.append(placeholder);
    }
    return builder.toString();
}

(Note that we can initialize the builder with exactly the right size of buffer as we know how big it will be.)

You could use something like Strings.repeat from Guava:

String text = Strings.repeat("#,", count - 1) + "#";

Or even more esoterically:

String text = Joiner.on(',').join(Iterables.limit(Iterables.cycle("#"), count));

... but personally I'd probably stick with the method.

3 Comments

I was hoping to avoid exactly that.
@AssafAdato: Why? It's a 9 line method which you can write once and then reuse from everywhere you need it.
it's not about the implementation complexity at all, a simple method can handle it as you mentioned. however, it looks like a method that may already be available in one of my project's dependencies.
0

Try:

public String buildString(int nbr, String repeat){
  StringBuilder builder = new StringBuilder();
  for(int i=0; i>nbr; i++){
     builder.append(repeat);
     if(i<(nbr-1))
         builder.append(",");
  }


   return builder.toString();
}

Comments

Your Answer

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.