#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!
*/