What you could do is use a StringBuilder
that will be initialized with your input String
, then use setCharAt(int index, char ch)
to modify a given char, this way you avoid building a new String
at each iteration as you currently do with the operator +=
on String
.
Something like:
public String everyNth(String str, int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be greater than 0");
}
StringBuilder result = new StringBuilder(str);
// This will replace every nth character with '-'
for (int i = n - 1; i < str.length(); i += n) {
result.setCharAt(i, '-');
}
return result.toString();
}
NB: Starts from n - 1
unless you want to replace the first character too if so starts from 0
.
If you want to simply remove the characters, you should use the method append(CharSequence s, int start, int end)
to build the content of your target String
, as next:
public String everyNth(String str, int n) {
if (n < 1) {
throw new IllegalArgumentException("n must be greater than 0");
}
StringBuilder result = new StringBuilder();
// The index of the previous match
int previous = 0;
for (int i = n-1; i < str.length(); i += n) {
// Add substring from previous match to the current
result.append(str, previous, i);
// Set the new value of previous
previous = i + 1;
}
// Add the remaining sub string
result.append(str, previous, str.length());
return result.toString();
}
3
solved Replace every nth character with “-” in java without regex