Vinay Vinay - 4 years ago 183
Java Question

Swap first two characters, then next two characters in a String using Java

I have been trying this program for a while now but not able to get a right solution to it. For example, the input is

123456
, which is entered by the user. I want to swap the first two characters, then the next two and so on. So, the output should be
214365
. I have tried the following code but not able to get the desired output.

public static void main(String[] arg$) {

Scanner in = new Scanner(System.in);
System.out.println("enter a word: ");
String str = in.nextLine();

char[] arr = str.toLowerCase().toCharArray();
char temp1, temp2;
for (int i = 0; i < arr.length; i++) {

try {
if ((i % 2) == 0) {
temp2 = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp2;
} else {
System.out.println(Arrays.toString(arr));
temp1 = arr[i + 1];
arr[i + 1] = arr[i+2];
arr[i + 2] = temp1;

}

} catch (Exception e) {

}
}
System.out.println("The final String is : =\n\n");
for (int j = 0; j < arr.length; j++) {
System.out.println(arr[j]);
}
}



Sample Input:

123456

Sample Output:

213456

Answer Source

You are swapping the first character with the second, and then the second with the third, and so on. That's not what you are supposed to do.

There should be at most n/2 swaps for a String of n characters (the number of swaps will be smaller than n/2 if n is odd).

for (int i = 0; i < arr.length; i+=2) {
    if (i + 1 < arr.length) {
        temp2 = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp2;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download