简体   繁体   中英

Swapping letters in a word (Java)

I have this 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 ay

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.

Java is a zero-based index language. Use these values:

int i = 1; // the first "a"
int j = 3; // the first "e"

substring() 's end parameter is exclusive - see bug fix below!

Try coding like this for clarity and debug-ability:

String first = str.substring(0, i);
char second = str.charAt(j);
String third = str.substring(i + 1, j); // Note: corrected bug!
char fourth = str.charAt(i);
String fifth = str.substring(j + 1);

System.out.println(first + second + third + fourth + fifth);

See live demo .

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, ie if you want the substring to include j-1, you have to set the parameter as j.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM