Advertisement
javatechie

Reverse a String Without Special Character

Aug 20th, 2020
1,777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1.  
  2. public class ReverseStringWithoutSpecialCharacter {
  3.  
  4.     public String reverse(String input) {
  5.         char temp = 0;
  6.         char[] ch = input.toCharArray();
  7.         for (int i = 0, j = input.length() - 1; i < j; ) {
  8.             if (isAlphaNumeric(String.valueOf(ch[i])) &&
  9.                     isAlphaNumeric(String.valueOf(ch[j]))) {
  10.                 temp = ch[i];
  11.                 ch[i] = ch[j];
  12.                 ch[j] = temp;
  13.                 i++;
  14.                 j--;
  15.             } else if (!isAlphaNumeric(String.valueOf(ch[i]))) {
  16.                 i++;
  17.             } else if (!isAlphaNumeric(String.valueOf(ch[j]))) {
  18.                 j--;
  19.             }
  20.         }
  21.         return String.valueOf(ch);
  22.     }
  23.  
  24.  
  25.     public boolean isAlphaNumeric(String s) {
  26.         String pattern = "^[a-zA-Z0-9]*$";
  27.         return s.matches(pattern);
  28.     }
  29.  
  30.     public static void main(String[] args) {
  31.         ReverseStringWithoutSpecialCharacter reverseStringWithoutSpecialCharacter = new ReverseStringWithoutSpecialCharacter();
  32.         System.out.println(reverseStringWithoutSpecialCharacter.reverse("Basant@gmail.com"));
  33.     }
  34. }
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement