How to reverse only the alphabetic characters in a string, keeping other characters in place with C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <cctype>

std::string reverseOnlyAlphabeticCharacters(std::string s) {
    int i = 0;
    int j = static_cast<int>(s.size()) - 1;

    while (i < j) {
        if (!std::isalpha(static_cast<unsigned char>(s[i]))) {
            ++i;
        } else if (!std::isalpha(static_cast<unsigned char>(s[j]))) {
            --j;
        } else {
            std::swap(s[i], s[j]);
            ++i;
            --j;
        }
    }

    return s;
}

int main() {
    std::string s = "a1-bC2-dEf3-ghIj";

    std::cout << s << "\n";
    std::cout << reverseOnlyAlphabeticCharacters(s) << "\n";
}


  
/*
run:
  
a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba
 
*/

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...