Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Reverse an array without affecting special characters?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.79k
    Comment on it

    Program to Reverse an array without affecting special characters in C++

    using namespace std;
    
    bool isAlphabet(char x)    // Function returns true if an alphabet
    {
        return ( (x >= 'A' && x <= 'Z') ||
                (x >= 'a' && x <= 'z') );
    }
    
    void reverse(char str[])
    {
        int right = strlen(str) - 1, left = 0;  //Initialize left and right pointers
        while (left < right)  //Traverse from both ends until left is greater then right
        {
            if (!isAlphabet(str[left]))  //To ignore special characters
                left++;
            else if(!isAlphabet(str[right]))
                right--;
    
            else      // Both str[left] and str[right] are not special then swap elements of left and right
            {
    
                char s = str[left];
                str[left] = str[right];
                str[right] = s;
                left++;
                right--;
            }
        }
    }
    int main()
    {
        char str[] = "a!!!b.c.d,e'f,ghi";
        cout << "Input string: " << str << endl;
        reverse(str);
        cout << "Output string: " << str << endl;
        return 0;
    }
    

    Output:
    Input string: a!!!b.c.d,e'f,ghi
    Output string: i!!!h.g.f,e'd,cba

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: