交换字符,第一个和最后一个

时间:2013-12-05 22:19:08

标签: java character swap

如何将字符串的前三个字母与最后三个字母交换?

我需要使用indexOf或类似的东西吗?我是一个java新手,并希望得到一些帮助。感谢。

1 个答案:

答案 0 :(得分:0)

public static String swap (String entry){

    char[] characters = entry.toCharArray();

    if (entry.length() < 6){
        return null; // cannot swap if length is under 6!
    }

    char tempchar;

    tempchar = characters[0];
    characters[0] = characters[characters.length-1];
    characters[characters.length-1] = tempchar;

    tempchar = characters[1];
    characters[1] = characters[characters.length-2];
    characters[characters.length-2] = tempchar;

    tempchar = characters[2];
    characters[2] = characters[characters.length-3];
    characters[characters.length-3] = tempchar;

    return String.copyValueOf(characters);
}