What is a simple way to repeat a string in java

+1 vote

I'm looking for a simple commons method or operator that allows me to repeat some String n times. I know I could write this using a for loop, but I wish to avoid for loops whenever necessary and a simple direct method should exist somewhere.

String str = "abc";
String repeated = str.repeat(3);

repeated.equals("abcabcabc");

Related to:

repeat string javascript Create NSString by repeating another string a given number of times

I try to avoid for loops when they are not completely necessary because:

  1. They add to the number of lines of code even if they are tucked away in another function.

  2. Someone reading my code has to figure out what I am doing in that for a loop. Even if it is commented and has meaningful variables names, they still have to make sure it is not doing anything "clever".

  3. Programmers love to put clever things in for loops, even if I write it to "only do what it is intended to do", that does not preclude someone coming along and adding some additional clever "fix".

  4. They are very often easy to get wrong. For loops involving indexes tend to generate off by one bugs.

  5. For loops often reuse the same variables, increasing the chance of really hard to find scoping bugs.

  6. For loops increase the number of places a bug hunter has to look.

Aug 27, 2018 in Java by Neha
• 6,300 points
18,503 views

4 answers to this question.

0 votes

From Java 11 on, there's a method String::repeat that does exactly what you asked for:

String str = "abc";
String repeated = str.repeat(3);
repeated.equals("abcabcabc");

Its Javadoc says:

/**
 * Returns a string whose value is the concatenation of this
 * string repeated {@code count} times.
 * <p>
 * If this string is empty or count is zero then the empty
 * string is returned.
 *
 * @param count number of times to repeat
 *
 * @return A string composed of this string repeated
 * {@code count} times or the empty string if this
 * string is empty or count is zero
 *
 * @throws IllegalArgumentException if the {@code count} is
 * negative.
 *
 * @since 11
 */ 

Here is the shortest version (Java 1.5+ required):

repeated = new String(new char[n]).replace("\0", s);

Where n is the number of times you want to repeat the string and s is the string to repeat.

No imports or libraries needed.

answered Aug 28, 2018 by Frankie
• 9,810 points
Thanks Frankie for this code, I used it in my java project at school.
0 votes

Here is the shortest version (Java 1.5+ required):

repeated = new String(new char[n]).replace("\0", s);

Where n is the number of times you want to repeat the string and s is the string to repeat.

No imports or libraries needed.

answered Dec 16, 2020 by Roshni
• 10,420 points
0 votes

String repeat() – Repeat string N times in Java

Learn to repeat a given string N times, to produce a new string that contains all the repetitions, though a simple Java program. We will use method Sting.repeat(N) (since Java 11) and using regular expression

1. String.repeat() API [Since Java 11]

This method returns a string whose value is the concatenation of given string repeated count times. If the string is empty or count is zero then the empty string is returned.

1.1. Syntax
/**

* Parameters:

* count - number of times to repeat

*

* Returns:

* A string composed of this string repeated count times or the empty string if this string is empty or count is zero

*

* Throws:

* IllegalArgumentException - if the count is negative.

*/


public String repeat​(int count)
answered Dec 16, 2020 by Gitika
• 65,870 points
0 votes

There is already answer wriiten using StringBuilder without any external libraries.

But if your project contains Apache Common lang jar, you can use



  • public static String repeat(String str, 
  • int repeat) 

    Repeat a String repeat times to form a new String.

    
    
    
    • StringUtils.repeat(null, 2) = null 
    • StringUtils.repeat("", 0) = "" 
    • StringUtils.repeat("", 2) = "" 
    • StringUtils.repeat("a", 3) = "aaa" 
    • StringUtils.repeat("ab", 2) = "abab" 
    • StringUtils.repeat("a", -2) = "" 

      StringUtils (Apache Commons Lang 3.7 API)

      It has lot of utility classes which always reduces boiler plate code from your project.

      answered Dec 16, 2020 by Rajiv
      • 8,880 points

      Related Questions In Java

      0 votes
      2 answers

      What is the easiest way to iterate through the characters of a string in Java?

      There are two approaches to this: for(int i ...READ MORE

      answered Aug 19, 2019 in Java by Sirajul
      • 58,990 points
      467 views
      0 votes
      1 answer

      What is the simplest way to read JSON from a URL in java

      Read json from url use url.openStream() and read contents ...READ MORE

      answered Jun 13, 2018 in Java by samarth295
      • 2,200 points
      3,116 views
      0 votes
      1 answer

      What is an efficient way to implement a singleton pattern in Java?

      Use an enum: public enum Foo { ...READ MORE

      answered Jul 6, 2018 in Java by Akrati
      • 3,170 points
      271 views
      0 votes
      2 answers

      What's the best way to check if a String represents an integer in Java?

      You can also use regular expression. str.matches("-?\\d+"); It will ...READ MORE

      answered Aug 9, 2018 in Java by Daisy
      • 8,110 points
      2,083 views
      0 votes
      3 answers

      Check if a String is numeric in Java

      Java 8 Lambda Expression is used: String someString ...READ MORE

      answered Sep 3, 2018 in Java by Daisy
      • 8,110 points
      2,108 views
      0 votes
      2 answers

      Generate an alpha-numeric string randomly

      Java supplies a way of doing this ...READ MORE

      answered Jul 18, 2018 in Java by Daisy
      • 8,110 points
      1,124 views
      0 votes
      1 answer

      How do I create a Java string from the contents of a file?

      If you're looking for an alternative that ...READ MORE

      answered Apr 19, 2018 in Java by Rishabh
      • 3,620 points
      378 views
      0 votes
      2 answers

      Counting no of Occurrence of a particular character inside a string in Java

      We can find out the no. of ...READ MORE

      answered Sep 7, 2018 in Java by Sushmita
      • 6,890 points
      1,099 views
      0 votes
      1 answer

      Which is the standard concise way to copy a file in Java?

      As toolkit mentions above, Apache Commons IO ...READ MORE

      answered Nov 15, 2018 in Java by Frankie
      • 9,810 points
      95 views
      0 votes
      2 answers

      In Java, what is the best way to determine the size of an object?

      I happened to find a java class "jdk.nashorn.internal.ir.debug.ObjectSizeCalculator", ...READ MORE

      answered Aug 19, 2019 in Java by Sirajul
      • 58,990 points
      3,727 views