Swapping Characters in a String in Java

后端 未结 3 1351
遥遥无期
遥遥无期 2021-01-26 06:47

Given the above excerpt from a Java code, I need to modify the code such that it could recursively swap pairs of the content of the string variable, \"locationAddress\". Please

3条回答
  •  不思量自难忘°
    2021-01-26 07:35

    Here's one solution with StringBuilder:

    public static String swapAdjacentPairs(String s) {
        StringBuilder sb = new StringBuilder(s);
        // divide 2 and then multiply by 2 to handle cases where the string length is odd
        // we always want an even string length
        // also note the i += 2
        for (int i = 0 ; i < (s.length() / 2 * 2) ; i += 2) {
            swapAdjacent(sb, i);
        }
        return sb.toString();
    }
    
    private static void swapAdjacent(StringBuilder sb, int index) {
        char x = sb.charAt(index);
        sb.setCharAt(index, sb.charAt(index + 1));
        sb.setCharAt(index + 1, x);
    }
    

    Usage:

    System.out.println(swapAdjacentPairs("abcdefghi"));
    

提交回复
热议问题