Java Program to Reverse String But Not Special Characters - Java Inspires
package basics; import java.util.ArrayList; import java.util.List; public class MainApp { public static void main(String[] args) { String s1 = "AA&D#U"; // expected is UD&A#A char[] chars = s1.toCharArray(); List<Character> charsS = new ArrayList<Character>(); List<Character> sPcharsS = new ArrayList<Character>(); for (Character c : chars) { if (Character.isAlphabetic(c)) { charsS.add(c); } else { sPcharsS.add(c); } } char[] rev = new char[s1.length()]; for (int i = 0; i < s1.length(); i++) { if (Character.isAlphabetic(chars[i])) { rev[i] = charsS.get(charsS.size() - 1); charsS.remove(charsS.size() - 1); } else { rev[i] = sPcharsS.get(0); sPcharsS.remove(0); } } System.out.println(String.copyValueOf(rev)); } }
UD&A#A