Simple way to repeat a string

后端 未结 30 3096
清酒与你
清酒与你 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

    If you are using Java <= 7, this is as "concise" as it gets:

    // create a string made up of n copies of string s
    String.format("%0" + n + "d", 0).replace("0", s);
    

    In Java 8 and above there is a more readable way:

    // create a string made up of n copies of string s
    String.join("", Collections.nCopies(n, s));
    

    Finally, for Java 11 and above, there is a new repeat​(int count) method specifically for this(link)

    "abc".repeat(12);
    

    Alternatively, if your project uses java libraries there are more options.

    For Apache Commons:

    StringUtils.repeat("abc", 12);
    

    For Google Guava:

    Strings.repeat("abc", 12);
    

提交回复
热议问题