Swapping Characters in a String in Java

后端 未结 3 1340
遥遥无期
遥遥无期 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:45

    A solution using Stream:

    String input = "abcdefghijk";
    String swapped = IntStream.range(0, input.length())
            .map(i -> i % 2 == 0 ? i == input.length() - 1 ? i : i + 1 : i - 1)
            .mapToObj(input::charAt)
            .map(String::valueOf)
            .collect(Collectors.joining());
    System.out.println(swapped); // badcfehgjik
    

    The swapping is driven by the index i. If i is even and there is a next (i+1) character then it's used. If i is odd then the previous (i-1) character is used.

提交回复
热议问题