Java String repeat a String for certain times to form a new String

Description

Java String repeat a String for certain times to form a new String


public class Main {
    public static void main(String[] argv) throws Exception {
        String string = "demo2s.com";
        int length = 2;
        System.out.println(makeLongRepeatString(string, length));
    }/*from   www.  ja v  a  2s .  co  m*/

    public static String makeLongRepeatString(String string, int length) {
        if (string == null) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            buffer.append(string);
        }
        return buffer.toString();
    }
}

Repeat a String <code>repeat</code> times to form a new String.

repeat(null, 2) = null
repeat("", 0)   = ""
repeat("", 2)   = ""
repeat("a", 3)  = "aaa"
repeat("ab", 2) = "abab"
repeat("a", -2) = ""
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com";
    int repeat = 2;
    System.out.println(repeat(str, repeat));
  }//from   www  . ja va  2s.  c  o m
  public static final String EMPTY = "";

  public static String repeat(String str, int repeat) {
    if (str == null) {
      return null;
    }
    if (repeat <= 0) {
      return EMPTY;
    }
    int inputLength = str.length();
    if (repeat == 1 || inputLength == 0) {
      return str;
    }
    if (inputLength == 1 && repeat <= PAD_LIMIT) {
      return padding(repeat, str.charAt(0));
    }

    int outputLength = inputLength * repeat;
    switch (inputLength) {
    case 1:
      char ch = str.charAt(0);
      char[] output1 = new char[outputLength];
      for (int i = repeat - 1; i >= 0; i--) {
        output1[i] = ch;
      }
      return new String(output1);
    case 2:
      char ch0 = str.charAt(0);
      char ch1 = str.charAt(1);
      char[] output2 = new char[outputLength];
      for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
        output2[i] = ch0;
        output2[i + 1] = ch1;
      }
      return new String(output2);
    default:
      StringBuffer buf = new StringBuffer(outputLength);
      for (int i = 0; i < repeat; i++) {
        buf.append(str);
      }
      return buf.toString();
    }
  }

  /**
   * <p>
   * Returns padding using the specified delimiter repeated to a given length.
   * </p>
   *
   * <pre>
   * padding(0, 'e')  = ""
   * padding(3, 'e')  = "eee"
   * padding(-2, 'e') = IndexOutOfBoundsException
   * </pre>
   */
  private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
    if (repeat < 0) {
      throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
    }
    final char[] buf = new char[repeat];
    for (int i = 0; i < buf.length; i++) {
      buf[i] = padChar;
    }
    return new String(buf);
  }
  private static final int PAD_LIMIT = 8192;
}



PreviousNext

Related