Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8055862

Provide a String repeat method

    Details

    • Type: Bug
    • Status: Closed
    • Priority: P4
    • Resolution: Duplicate
    • Affects Version/s: 8u20
    • Fix Version/s: None
    • Component/s: core-libs
    • Labels:
    • Subcomponent:
    • CPU:
      x86
    • OS:
      windows_7

      Description

      A DESCRIPTION OF THE REQUEST :
      I'd like an instance method on class String that will repeat the string. E.g., "0".repeat(8) would be "00000000".

      Guava and Apache Commons provide this functionality, and several other languages have it as a built-in, which shows it is a commonly wanted feature. A method on class String itself can do it most efficiently, because it can avoid duplicating the array on construction. It is also a more convenient place to have it, rather than having to import string util classes in external libraries.

      A suggested implementation, written by me, released to public domain:

          /**
           * Returns a string that consists of this string repeated some number of times.
           *
           * @param count the number of times to repeat this string
           * @return a string of {@code count} copies of this string
           * @throws IllegalArgumentException if {@code count} is negative
           */
          public String repeat(int count) {
              if (count < 0) throw new IllegalArgumentException("Repeat count is negative");
              if (count == 1) return this;
              int length = length();
              if (count == 0 || length == 0) return "";
              if ((long)count * length > Integer.MAX_VALUE)
                  throw new OutOfMemoryError();
              char[] out = new char[count * length];
              if (length == 1) {
                  Arrays.fill(out, value[0]);
              } else {
                  for (int i = 0; i < out.length; i += length)
                      System.arraycopy(value, 0, out, i, length);
              }
              return new String(out, true); // uncopied array
          }

      JUSTIFICATION :
      .


        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                webbuggrp Webbug Group
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: