Java’s String Repeat Implementation


In Python, we can use * to repeat a string. For example:

1
2
"abc" * 3 # "abcabcabc"
"h" * 2   # "hh"
"abc" * 3 # "abcabcabc"
"h" * 2   # "hh"

We can use the following Java function to generate a string that repeats s n times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class StringUtils {
  public static String repeat(String s, int n) {
    if (1 == s.length()) {
      var bb = new byte[n];
      Arrays.fill(bb, s.getBytes()[0]);
      return new String(bb);
    } else {
      var ret = new StringBuilder();
      for (int i = 0; i < n; i++) {
        ret.append(s);
      }
      return ret.toString();
    }
  }
}
public class StringUtils {
  public static String repeat(String s, int n) {
    if (1 == s.length()) {
      var bb = new byte[n];
      Arrays.fill(bb, s.getBytes()[0]);
      return new String(bb);
    } else {
      var ret = new StringBuilder();
      for (int i = 0; i < n; i++) {
        ret.append(s);
      }
      return ret.toString();
    }
  }
}

For example:

1
var s = StringUtils.repeat("hello", 2); // "hellohello"
var s = StringUtils.repeat("hello", 2); // "hellohello"

If the given pattern is size of one, we can use Arrays.fill to achieve a much higher performance otherwise we use the StringBuilder to repeat the pattern the given number of times.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
215 words
Last Post: Teaching Kids Programming - Depth First Search Algorithm to Determine Sum Binary Tree
Next Post: Teaching Kids Programming - Remove One Number to Make Average

The Permanent URL is: Java’s String Repeat Implementation

Leave a Reply