1

I want to repeat a string X times in Android Java.

This, as I understand it, is not a good option:

StringUtils.repeat("abc", 50);

Because it would require

import org.apache.commons.lang.StringUtils; // External libary --- cannot use

So what is the best way to repeat a string X times for Android in Java?

2 Answers 2

5

You could use a stringbuilder and a regular loop. Inside the loop, append the string to the stringbuilder, and then after the loop print the string from the builder.

StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 50; i++) {
    stringBuilder.append("xyz");
}
String resultString = stringBuilder.toString();
Sign up to request clarification or add additional context in comments.

1 Comment

Could you provide an example?
2

You can create your own StringUtils class which has a repeat function that does that, for example:

public class StringUtils{
     public static String repeat(String val, int count){
          StringBuilder buf = new StringBuilder(val.length() * count);
          while (count-- > 0) {
               buf.append(val);
          }
          return buf.toString();
     }
}

6 Comments

Probably don't want to do this, because since Strings are immutable that "ret += val" will be creating new string objects every time. It's better to use something like a stringbuilder when there's a variable number of strings that would need to be built along the way.
Very bad example. Don't use String += String. Never use String += String in a loop. Use a StringBuilder.
@Andreas thanks for the suggestions, I will change my example to use a StringBuilder instead.
A couple of syntax errors ... String str instead of String val and new StringBuilder(count) instead of StringBuilder(outputLength). But otherwise, looks good. Thanks!
Also, you can reduce your variable count by replacing for (int i = 0; i < count; i++) with for (;count >= 0; count--).
|

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.