Write the program to reverse a string with maintaining special character position?

-->

Reverse a string with maintaining special character position.

Algorithm :

  1. Let input string be ‘inputArray[]’ and length of string be ‘length’
  2. left = 0, right = length-1
  3. While left is smaller than right, do following
  4. If inputArray[left] is not an alphabetic character, do left++
  5. Else If inputArray[right] is not an alphabetic character, do right–
  6. Else swap inputArray[left] and inputArray[right]

Input/Output :

Input:
#eMexo@gmail.com#

Output:
#mocli@amgox.eMe#

Input: 
#eMexo@gmail.com# 
Output: 
#mocli@amgox.eMe#

Program:

package com.emexo.programmingchallenge;

import java.util.Scanner;

public class ReverseString {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = scan.nextLine();
        System.out.println("Input String  :   " + input);

        String output = reverse(input);
        System.out.println("Reversed String : " + output);
    }

    /**
     * Reverse a string with maintaining special character position.
     * Algorithm :
     * 1) Let input string be 'inputArray[]' and length of string be 'length'
     * 2) left = 0, right = length-1
     * 3) While left is smaller than right, do following
     * a) If inputArray[left] is not an alphabetic character, do left++
     * b) Else If inputArray[right] is not an alphabetic character, do right--
     * c) Else swap inputArray[left] and inputArray[right]
     *
     * @param input : Input string
     * @return reverse string
     */
    public static String reverse(String input) {
        char[] inputArray = input.toCharArray();
        // length of the array
        int length = inputArray.length;

        int left = 0;
        int right = length - 1;

        while (left < right) {
            // check if the first character is special character
            if (String.valueOf(inputArray[left]).matches("[^a-z A-Z 0-9]")) {
                left++;
                // check if the last character is special character
            } else if (String.valueOf(inputArray[right]).matches("[^a-z A-Z 0-9]")) {
                right--;
            } else {
                char temp = inputArray[left];
                inputArray[left] = inputArray[right];
                inputArray[right] = temp;
                left++;
                right--;
            }
        }
        return String.valueOf(inputArray);
    }
}