In Python, we can use * to repeat a string. For example:
"abc" * 3 # "abcabcabc"
"h" * 2 # "hh"
We can use the following Java function to generate a string that repeats s n times.
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:
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) —
198 wordsLast Post: Teaching Kids Programming - Depth First Search Algorithm to Determine Sum Binary Tree
Next Post: Teaching Kids Programming - Remove One Number to Make Average