Reverse Each Word in a String
Problem and examples
Given a string containing one or more words separated by spaces, your task is to reverse each word individually, while keeping the order of words the same.
Each word is defined as a sequence of characters separated by spaces. Spaces should be preserved between words, but the characters of each word should appear in reverse order.
This operation should not affect extra spaces or punctuation. The final result should be a single string with all words reversed.
| Input String | Output String | Description |
|---|---|---|
| "hello world" | "olleh dlrow" | Each word is reversed individually |
| "data structures" | "atad serutcurts" | Two words reversed, order remains |
| " a b c " | " a b c " | Single-letter words are the same; spaces preserved |
| " hello world " | " olleh dlrow " | Multiple spaces between and around words are preserved |
| "example" | "elpmaxe" | Single word reversed |
| " " | " " | Only spaces, no words to reverse |
| "" | "" | Empty string returns empty string |
Explore Reverse Every Word in a String
Load an example or enter your own input. Use the player controls to follow each change.
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.
- Split the input string using space as delimiter into a list of words.
- Iterate through each word in the list.
- For each word, reverse its characters using a loop or inbuilt reverse method.
- Join all the reversed words using a single space.
- Return the resulting string.
Implementation and efficiency
C implementation
#include <stdio.h>
#include <string.h>
void reverse(char* str, int start, int end) {
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
void reverseEachWord(char* str) {
int i = 0, start = 0;
while (str[i]) {
if (str[i] == ' ' || str[i + 1] == '\0') {
int end = (str[i] == ' ') ? i - 1 : i;
reverse(str, start, end);
start = i + 1;
}
i++;
}
}
int main() {
char str[] = "Hello World";
reverseEachWord(str);
printf("Reversed: %s\n", str);
return 0;
}C++ implementation
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
string reverseEachWord(string s) {
istringstream iss(s);
string word, result;
while (iss >> word) {
reverse(word.begin(), word.end());
result += word + " ";
}
if (!result.empty()) result.pop_back();
return result;
}
int main() {
string input = "Hello World";
cout << "Reversed: " << reverseEachWord(input) << endl;
return 0;
}Python implementation
def reverse_each_word(s):
words = s.split(' ')
reversed_words = [word[::-1] for word in words]
return ' '.join(reversed_words)
input_str = "Hello World"
print("Reversed:", reverse_each_word(input_str))Java implementation
public class ReverseWords {
public static String reverseEachWord(String s) {
String[] words = s.split(" ", -1);
StringBuilder result = new StringBuilder();
for (int i = 0; i < words.length; i++) {
StringBuilder word = new StringBuilder(words[i]);
result.append(word.reverse());
if (i != words.length - 1) result.append(" ");
}
return result.toString();
}
public static void main(String[] args) {
String input = "Hello World";
System.out.println("Reversed: " + reverseEachWord(input));
}
}JavaScript implementation
function reverseEachWord(s) {
const words = s.split(' ');
const reversedWords = words.map(word => word.split('').reverse().join(''));
return reversedWords.join(' ');
}
const input = "Hello World";
console.log("Reversed:", reverseEachWord(input));Go implementation
package main
import (
"fmt"
"strings"
)
func reverseWord(word string) string {
runes := []rune(word)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func reverseEachWord(s string) string {
words := strings.Split(s, " ")
for i, word := range words {
words[i] = reverseWord(word)
}
return strings.Join(words, " ")
}
func main() {
input := "Hello World"
fmt.Println("Reversed:", reverseEachWord(input))
}Rust implementation
fn reverse_each_word(s: &str) -> String {
s.split_whitespace()
.map(|w| w.chars().rev().collect::<String>())
.collect::<Vec<_>>()
.join(" ")
}
fn main() {
let input = "Hello World";
println!("Reversed: {}", reverse_each_word(input));
}Kotlin implementation
fun reverseEachWord(s: String): String {
return s.split(" ").joinToString(" ") { it.reversed() }
}
fun main() {
val input = "Hello World"
println("Reversed: ${reverseEachWord(input)}")
}Swift implementation
func reverseEachWord(_ s: String) -> String {
return s.split(separator: " ").map { String($0.reversed()) }.joined(separator: " ")
}
let input = "Hello World"
print("Reversed:", reverseEachWord(input))TypeScript implementation
function reverseEachWord(s: string): string {
return s.split(' ').map(word => word.split('').reverse().join('')).join(' ');
}
const input = "Hello World";
console.log("Reversed:", reverseEachWord(input));Time complexity
| Case | Time | Explanation |
|---|---|---|
| best case | O(n) | We scan each character in the string once during splitting, reversing, and joining. |
| average case | O(n) | Each word is reversed individually, and all characters are processed linearly. |
| worst case | O(n) | Even if the string has long words or many spaces, we still traverse each character only once. |
Space complexity
O(n)
A new string is built to store the reversed output, proportional to the input size.