1. 程式人生 > >面試題:一個字串包含英文和特殊字元,特殊字元不變,英文順序反過來,比如string str="[email 

面試題:一個字串包含英文和特殊字元,特殊字元不變,英文順序反過來,比如string str="[email 

public class Reverse {

    public static void main(String[] args) {
        String str = "[email protected]!tk";
        char[] chars = str.toCharArray();
        for (int i = 0, j = chars.length - 1; i < j; j--, i++) {
            if (!isEnglish(String.valueOf(chars[i]))) {
                i++;
            }
            if (!isEnglish(String.valueOf(chars[j]))) {
                j--;
            }
            char tmp = chars[i];
            chars[i] = chars[j];
            chars[j] = tmp;
        }
        for (int x = 0; x < chars.length; x++) {
            System.out.print(chars[x]);
        }
    }

    private static boolean isEnglish(String ch){
        return ch.matches("^[a-zA-Z]*");
    }
}

結果:

[email protected]!dw