Home > other >  Change letters of a string at certain points
Change letters of a string at certain points

Time:07-31

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?

CodePudding user response:

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);

CodePudding user response:

You can try the below solution:

    String ans = "";
    String a = "abcdefghijk";

    for (int j = 0; j < a.length(); j   )
    {
        if(j==0 )
        {
            ans = ans Character.toString(a.charAt(j));
        }
        else if( j%3 == 2)
        {
            ans = ans "X";
        }
        else
        {
            ans = ans Character.toString(a.charAt(j));
        }
    }
    System.out.println(ans);

CodePudding user response:

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();

CodePudding user response:

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());
  • Related