Simple way to repeat a string

后端 未结 30 3097
清酒与你
清酒与你 2020-11-21 06:55

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 f

30条回答
  •  后悔当初
    2020-11-21 07:02

    String::repeat

    ". ".repeat( 7 )  // Seven period-with-space pairs: . . . . . . . 
    

    New in Java 11 is the 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.
     * 

    * 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 */

提交回复
热议问题