Simple way to repeat a string

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

    using only JRE classes (System.arraycopy) and trying to minimize the number of temp objects you can write something like:

    public static String repeat(String toRepeat, int times) {
        if (toRepeat == null) {
            toRepeat = "";
        }
    
        if (times < 0) {
            times = 0;
        }
    
        final int length = toRepeat.length();
        final int total = length * times;
        final char[] src = toRepeat.toCharArray();
        char[] dst = new char[total];
    
        for (int i = 0; i < total; i += length) {
            System.arraycopy(src, 0, dst, i, length);
        }
    
        return String.copyValueOf(dst);
    }
    

    EDIT

    and without loops you can try with:

    public static String repeat2(String toRepeat, int times) {
        if (toRepeat == null) {
            toRepeat = "";
        }
    
        if (times < 0) {
            times = 0;
        }
    
        String[] copies = new String[times];
        Arrays.fill(copies, toRepeat);
        return Arrays.toString(copies).
                  replace("[", "").
                  replace("]", "").
                  replaceAll(", ", "");
    }
    

    EDIT 2

    using Collections is even shorter:

    public static String repeat3(String toRepeat, int times) {
        return Collections.nCopies(times, toRepeat).
               toString().
               replace("[", "").
               replace("]", "").
               replaceAll(", ", "");
    }
    

    however I still like the first version.

    0 讨论(0)
  • 2020-11-21 07:01

    Not the shortest, but (i think) the fastest way is to use the StringBuilder:

     /**
       * Repeat a String as many times you need.
       *
       * @param i - Number of Repeating the String.
       * @param s - The String wich you want repeated.
       * @return The string n - times.
       */
      public static String repeate(int i, String s) {
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < i; j++)
          sb.append(s);
        return sb.toString();
      }
    
    0 讨论(0)
  • 2020-11-21 07:01

    If you are worried about performance, just use a StringBuilder inside the loop and do a .toString() on exit of the Loop. Heck, write your own Util Class and reuse it. 5 Lines of code max.

    0 讨论(0)
  • 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.
     * <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
     */ 
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-21 07:02

    I created a recursive method that do the same thing you want.. feel free to use this...

    public String repeat(String str, int count) {
        return count > 0 ?  repeat(str, count -1) + str: "";
    }
    

    i have the same answer on Can I multiply strings in java to repeat sequences?

    0 讨论(0)
提交回复
热议问题