Write a method called swapPairs that accepts a String as a parameter and returns that String with each pair of adjacent letters reversed. If the String has an odd number of letters, the last letter is unchanged. For example, the call swapPairs("example") should return "xemalpe" and the call swapPairs("hello there") should return "ehll ohtree".
public class PairsSwap {
public static String swapPairs(String string) {
// convert that string to an array
char[] toChar = string.toCharArray();
// run through loop two characters at a time
for(int i = 0; i <= toChar.length - 2; i += 2) {
// swap function
char var = toChar[i];
toChar[i] = toChar[i+1];
toChar[i+1] = var;
}
// convery string of characters into string again
String swappedString = new String(toChar);
return swappedString;
}
public static void main(String[] args) {
String swapped = PairsSwap.swapPairs("kishore");
System.out.println("string after apply swapping: " +swapped);
}
}
Output:
string after apply swapping: ikhsroe
}