Program to reverse String without reversing special characters (Optimized Solution)
Code:
public class Practice3 {
public static void main(String[] args) {
String
str = "ABC@DEF#GHI";
int len = str.length();
char[] arr = str.toCharArray();
for(int i = 0, j = len-1; i<j;) {
if(!Character.isAlphabetic(arr[i]))
i++;
else if(!Character.isAlphabetic(arr[j]))
j--;
else {
//Swap
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
String
reversed = new String(arr);
System.out.println(reversed);
}
}
Output:
IHG@FED#CBA