Home » Interview Questions » String Interview Questions » Reverse a string without affecting special characters

Reverse a string without affecting special characters


()

Given a string which contains special characters(such as %,&,*,^,$) and alphabets(‘a’ to ‘z’ and ‘A’ to ‘Z’), write a function that will reverse the string in a way that special characters are not affected

Example

INPUT
s = “[email protected]&d”

OUTPUT
[email protected]&a”

Method 1(Simple Solution)

Algorithm

1. Create a auxilary string ‘t’ and store all the alphabetic characters in string ‘t’

2. Now, reverse the string ‘t’

3. Now, Traverse the input string and string ‘t’ at a time

a. If there is a alphabetic character in input string, then replace it with the character in string ‘t’
b. If the character in input string is not a alphabetic character, then just move to the next character

Method 2(Eficient Solution)

In this method we will be not using extra space

Algorithm

1. Traverse the input string with  two varaibles l and r where l =0 and r = n-1, n is the length of the input string

2.  while l < r

a. if s[l] is not a alphabet, then do l++
b. else if s[r] is not a alphabet, then do r–
c. else swap the characters in s[l] and s[r] and so l++, r–

#include<bits/stdc++.h>
using namespace std;
 
// Returns true if x is an aplhabatic character, false otherwise
bool isAlphabet(char x)
{
    return ( (x >= 'A' &&  x <= 'Z') ||
             (x >= 'a' &&  x <= 'z') );
}
 
void reverseString(char s[])
{
    // Initialize l and r
    int r = strlen(s) - 1, l = 0;
 
    //Till l meets r, travers from both ends
    while (l < r)
    {
        // ignore special characters
        if (!isAlphabet(s[l]))
            l++;
        else if(!isAlphabet(s[r]))
            r--;
 
        else // if both s[l] and s[r] are alphabatical characters
        {
            swap(s[l], s[r]);
            l++;
            r--;
        }
    }
}

int main()
{
    char s[] = "[email protected]&d";
    cout << "Input string: " << s << endl;
    reverseString(s);
    cout << "Output string: " << s << endl;
    return 0;
}

Try It

READ  Longest Common Prefix using Trie

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions