Understanding the Problem
We are given a sentence made up of words separated by spaces. Our task is to reverse the characters of each word individually, but keep the word order and spacing exactly as in the original sentence.
In simple terms: "hello world"
should become "olleh dlrow"
.
This might sound straightforward, but we have to be careful with extra spaces, punctuation, or special characters. The idea is not to rearrange the words, just reverse each one while preserving the overall structure of the sentence.
Step-by-Step Solution with Example
Step 1: Split the string into words
We start by breaking the input string based on spaces. However, if we use a regular split()
function, it might collapse multiple spaces into one, which changes the formatting. So we need to find a way to preserve the spacing or use a manual method.
For example:
Input: "hello world"
Splitting normally gives: ["hello", "world"]
— notice the double space is lost.
We must preserve that structure.
Step 2: Reverse each word individually
Loop through each word and reverse its characters. For instance:
"hello"
→ "olleh"
"world"
→ "dlrow"
If we preserved spacing correctly in the previous step, we now replace each word with its reversed version in the same positions.
Step 3: Combine the reversed words with the correct spacing
After reversing each word, we reconstruct the sentence by joining them with the original spacing. If you’re manually processing characters and spaces, you can keep track of them using a loop.
For example:
Original: "hello world"
Reversed: "olleh dlrow"
We preserved the double space!
Edge Cases
- Empty string: If input is
""
, the output should also be ""
.
- Only spaces: If input is
" "
, then output should also be " "
. No words to reverse, but spacing must remain.
- Single word: Input like
"hello"
should give "olleh"
.
- Punctuation or symbols: If input has punctuation like
"hello!"
, it becomes "!olleh"
. We treat symbols as part of the word.
- Multiple spaces between words: We must ensure that all original spaces are retained exactly as they were.
Finally
This problem helps beginners learn about string manipulation, loops, and edge case handling. It also builds awareness of how certain built-in functions behave, especially with whitespace.
When solving string problems, always consider how the language’s functions treat whitespace, and whether they preserve or collapse it. Manual traversal often gives more control when formatting matters.
Practice with different kinds of inputs — clean sentences, extra spaces, empty strings, or symbols — to strengthen your understanding.
Comments
Loading comments...