How to reverse a string without affecting special characters in C++

1 Answer

0 votes
#include <iostream>
#include <cctype>
 
void reverseStringWithoutTheSpecialCharacters(std::string &str) {
    int right = str.length()  - 1, left = 0;
  
    while (left < right) {
        if (!isalpha(str[left]))
            left++;
        else if(!isalpha(str[right]))
            right--;
        else {
            std::swap(str[left], str[right]);
            left++;
            right--;
        }
    }
}
int main()
{
    std::string str = "ab*#cde!@$,fg{}";
     
    reverseStringWithoutTheSpecialCharacters(str);
     
    std::cout << str;
}
 
 
 
 
/*
run:
 
gf*#edc!@$,ba{}
 
*/

 



answered Aug 22, 2022 by avibootz
edited Aug 23, 2022 by avibootz
...