How to reverse a vector of characters without affecting the special characters in C++

1 Answer

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

/**
 * @brief Reverses only the alphabetic characters in a character vector in-place,
 *        leaving special characters, spaces, and digits in their original positions.
 * 
 * @param vec Reference to the character vector to modify.
 */
void reverseOnlyLetters(std::vector<char>& vec) {
    if (vec.empty()) {
        return; // Guard against empty vectors
    }

    int left = 0;
    int right = static_cast<int>(vec.size()) - 1;

    // Use a two-pointer approach moving inward from both ends
    while (left < right) {
        // Advance left pointer until it points to an alphabetic character
        while (left < right && !std::isalpha(static_cast<unsigned char>(vec[left]))) {
            left++;
        }
        
        // Move right pointer backward until it points to an alphabetic character
        while (left < right && !std::isalpha(static_cast<unsigned char>(vec[right]))) {
            right--;
        }

        // Swap the valid letters found at both pointers using std::swap
        if (left < right) {
            std::swap(vec[left], vec[right]);
            left++;
            right--;
        }
    }
}

int main() {
    // Input string converted to a standard vector of characters
    std::string input = "a#b$%c&*(def!";
    std::vector<char> vec(input.begin(), input.end());

    std::cout << "Original: ";
    for (char ch : vec) {
        std::cout << ch;
    }
    std::cout << '\n';

    // Apply the reversal function in-place
    reverseOnlyLetters(vec);

    std::cout << "Reversed: ";
    for (char ch: vec) {
        std::cout << ch;
    }
}


/*
run:

Original: a#b$%c&*(def!
Reversed: f#e$%d&*(cba!

*/

 



answered 2 days ago by avibootz

Related questions

...