How to reverse an array of characters without affecting the special characters in C++

2 Answers

0 votes
#include <iostream> 
#include <cstring>
 
bool is_letter(char x) { 
    return ((x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z')); 
} 
   
void reverse(char s[]) { 
    int right = strlen(s) - 1, left = 0; 
   
    while (left < right) { 
        if (!is_letter(s[left])) 
            left++; 
        else if (!is_letter(s[right])) 
                right--; 
             else { 
                std::swap(s[left], s[right]); 
                left++; 
                right--; 
             } 
    } 
} 
   
int main() 
{ 
    char s[] = "a#b$%c&*(def!"; 
 
    reverse(s); 
     
    std::cout << s;
} 
 
 
/*
run:
 
f#e$%d&*(cba!
 
*/
 

 



answered Jun 14, 2019 by avibootz
edited 5 days ago by avibootz
0 votes
#include <iostream>
#include <cstring>
#include <cctype>

/**
 * @brief Reverses only the alphabetic characters in a character array in-place,
 *        leaving special characters, spaces, and digits in their original positions.
 * 
 * @param str Pointer to the mutable null-terminated character array.
 */
void reverseOnlyLetters(char* str) {
    if (str == nullptr) {
        return; // Guard against null pointer dereferences
    }

    int left = 0;
    int right = static_cast<int>(std::strlen(str)) - 1;

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

        // Swap the valid letters found at both pointers
        if (left < right) {
            char temp = str[left];
            str[left] = str[right];
            str[right] = temp;

            left++;
            right--;
        }
    }
}

int main() {
    // Input string specified (must be a mutable array, not a read-only string literal)
    char s[] = "a#b$%c&*(def!";

    std::cout << "Original: " << s << '\n';

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

    std::cout << "Reversed: " << s << '\n';
}


/*
run:

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

*/

 



answered 5 days ago by avibootz

Related questions

...