When it comes to doing computations on String
, is it better to convert them to char
arrays and then work on them? So all String
problems are really array problems?
For instance, what would be the better method in terms of performance? What are the advantages/disadvantages?
public static String repeatEnd1(String str, int n) {
StringBuilder sb = new StringBuilder();
if (n <= str.length()) {
String lastChars = str.substring(str.length() - n);
for (int i = 0; i < n; i++) {
sb.append(lastChars);
}
}
return sb.toString();
}
public static String repeatEnd2(String str, int n) {
if (n > str.length()) {
return str;
}
char[] chars = str.toCharArray();
char[] lastN = Arrays.copyOfRange(chars, chars.length - n, chars.length);
char[] nLastN = new char[n * n];
int i = 0, j = 0;
while (i < nLastN.length) {
if (j > n - 1) {
j = 0;
}
nLastN[i++] = lastN[j++];
}
return String.valueOf(nLastN);
}