Swapping letters in a word (Java)

Tags:



I have this question: question

I tried solving the question through various integer values of i and j. But the most suitable ones I could find was 1 and 5. However even then the output was near to the correct version and not properly correct. Here’s my code:

public class test {
    public static void main(String[] args) {

        String str = "Gateway";
        int i = 1, j =5;
        String first = str.substring(0, i);
        System.out.println(first);
        char second = str.charAt(j);
        System.out.println(second);
        String third = str.substring(i + 1, j -1);
        System.out.println(third);
        System.out.println(str.charAt(i));
        System.out.println(str.substring(j + 1));
        
    }
}

This results in the output: G a te a y

Is there something wrong with my code or am I taking the wrong integer values? I’ve been trying to figure out but certainly that has been of no help. I hope somebody can point out the mistake I’m doing.

Answer

Two things:

  1. The choice of i and j, i = 1, and j = 3 (basically the indices of the letters to be swapped).
  2. String third = str.substring(i + 1, j - 1);

should be

String third = str.substring(i + 1, j);

as substring goes till the index just before the one mentioned in the second argument, i.e if you want the substring to include j-1, you have to set the parameter as j.



Source: stackoverflow