How to reverse only the alphabetic characters in a string, keeping other characters in place with Java

1 Answer

0 votes
public class Main {

    public static String reverseOnlyAlphabeticCharacters(String s) {
        char[] chars = s.toCharArray();
        int i = 0;
        int j = chars.length - 1;

        while (i < j) {
            if (!Character.isLetter(chars[i])) {
                i++;
            } else if (!Character.isLetter(chars[j])) {
                j--;
            } else {
                char tmp = chars[i];
                chars[i] = chars[j];
                chars[j] = tmp;
                i++;
                j--;
            }
        }

        return new String(chars);
    }

    public static void main(String[] args) {
        String s = "a1-bC2-dEf3-ghIj";

        System.out.println(s);
        System.out.println(reverseOnlyAlphabeticCharacters(s));
    }
}

 
 
/*
run:
 
a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/
 

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...