Reputation: 79
I get a string from the keyboard and I want every 3 letters in the string to change the original letter to an "X", but I'm having trouble doing this algorithm.
for example: if I have the string abcdefghij I have to return the string abXdeXfgXij or if i have hellokit string i need to return heXloXit
I've done this so far:
String ans = "";
String a = "abcdefghijk";
for (int j = 0; j < a.length(); j += 3) {
ans += a.substring(j, j+2) + x;
}
but it can happen to give the StringIndexOutOfBoundsException
error.
how can i do this without resulting in error?
Upvotes: 1
Views: 127
Reputation: 399
public static String replaceEvery3rdChar(String input)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++)
{
if ((i + 1) % 3 == 0)
{
result.append("X");
}
else
{
result.append(input.charAt(i));
}
}
return result.toString();
}
Upvotes: 0
Reputation: 16498
Simpler and shorter use regex:
String a = "abcabcabcab";
String regex = "(..)(.)";
String ans = a.replaceAll(regex,"$1X");
Strings should not be concatenated using '+' in a loop. If, how ever, you want to stick to that approach you should only itereate to the largest number multiple of three which is less than your input length. You also need to append possiblly not appended chars if your input length is not a multiple of three after the loop:
String a = "abcabcabcab";
String ans = "";
for (int j = 0; j < a.length() / 3 * 3; j += 3) {
ans += a.substring(j, j+2) + 'X';
}
ans += a.substring(ans.length());
Upvotes: 0
Reputation: 4652
String concatenation doesn't work optimally because of string is copying on every step of the loop, consider using StringBuilder
.
To solve your problem, just iterate on every char of the input string and copy every char to the output string builder, except for every third character (the character which index i
satisfies the equality i % 3 == 2
).
You will get something like this:
String input = "abcdefghijk";
StringBuilder output = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i % 3 == 2) {
output.append("X");
} else {
output.append(input.charAt(i));
}
}
String ans = output.toString();
Upvotes: 0
Reputation: 162
this works fine for me
String ans = "";
String a = "abcdefghij";
for(int i = 1; i<=a.length(); i++) {
if(i%3==0) {
ans += "X";
} else {
ans += a.charAt(i-1);
}
}
System.out.println(ans);
Upvotes: 3