Reverse Characters in Each Word
Learn how to reverse the characters within each word while keeping the word order intact. A common variation of the string reversal problem in coding interviews.
Detailed Explanation
Reversing Characters Within Each Word
This operation reverses the characters inside each word but keeps the words in their original order. It is a hybrid of character reversal and word-level preservation.
Example
Input: "Hello World"
Output: "olleH dlroW"
Each word is reversed individually, but "Hello" still comes before "World".
Implementation
JavaScript:
const result = str.replace(/\S+/g, word => [...word].reverse().join(""));
Python:
result = " ".join(word[::-1] for word in text.split(" "))
How It Differs from Other Modes
| Mode | Input | Output |
|---|---|---|
| Reverse characters | "Hello World" | "dlroW olleH" |
| Reverse words | "Hello World" | "World Hello" |
| Reverse each word | "Hello World" | "olleH dlroW" |
Preserving Whitespace
A common edge case is preserving the exact whitespace pattern. If the input has multiple spaces or tabs between words, the regex approach /\S+/g preserves them:
Input: "Hello World"
Output: "olleH dlroW"
Multi-line Support
When processing multi-line text, each line should be handled independently:
Input:
"Hello World"
"Good Morning"
Output:
"olleH dlroW"
"dooG gninroM"
Practical Applications
- Obfuscation: Light text scrambling that preserves word boundaries
- Word games: Creating puzzles where readers must mentally reverse each word
- Testing: Generating test data with reversed words while maintaining structure
Use Case
Reversing characters within each word is a common coding interview variation that tests understanding of string manipulation at multiple levels. It is also used in word puzzle generators, educational tools for teaching reading skills, and text obfuscation where structure must be preserved.