Given a string, the task is to reverse the order of the words in the given string.
Examples:
Input: s = “geeks quiz practice code”
Output: s = “code practice quiz geeks”Input: s = “i love programming very much”
Output: s = “much very programming love i”
Approach:
- Initially, reverse the individual words of the given string one by one, for the above example, after reversing individual words the string should be “i ekil siht margorp yrev hcum”.
- Reverse the whole string from start to end to get the desired output “much very program this like i” in the above example.
Follow the below steps to solve the problem:
- Run a for loop to traverse the string and create a temporary string to store the words
- If the current character is a space then add the current string to the answer and empty the string
- Else push the character into the string
- Print the answer array in reverse order
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using
namespace
std;
void
reverseWords(string s)
{
vector<string> tmp;
string str =
""
;
for
(
int
i = 0; i < s.length(); i++) {
if
(s[i] ==
' '
) {
tmp.push_back(str);
str =
""
;
}
else
str += s[i];
}
tmp.push_back(str);
int
i;
for
(i = tmp.size() - 1; i > 0; i--)
cout << tmp[i] <<
" "
;
cout << tmp[0] << endl;
}
int
main()
{
string s =
"i like this program very much"
;
reverseWords(s);
return
0;
}
C
#include <stdio.h>
void
reverse(
char
* begin,
char
* end)
{
char
temp;
while
(begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void
reverseWords(
char
* s)
{
char
* word_begin = s;
char
* temp = s;
while
(*temp) {
temp++;
if
(*temp ==
''
) {
reverse(word_begin, temp - 1);
}
else
if
(*temp ==
' '
) {
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
}
reverse(s, temp - 1);
}
int
main()
{
char
s[] =
"i like this program very much"
;
char
* temp = s;
reverseWords(s);
printf
(
"%s"
, s);
return
0;
}
Java
import
java.util.*;
class
GFG {
static
void
reverse(
char
str[],
int
start,
int
end)
{
char
temp;
while
(start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static
char
[] reverseWords(
char
[] s)
{
int
start =
0
;
for
(
int
end =
0
; end < s.length; end++) {
if
(s[end] ==
' '
) {
reverse(s, start, end);
start = end +
1
;
}
}
reverse(s, start, s.length -
1
);
reverse(s,
0
, s.length -
1
);
return
s;
}
public
static
void
main(String[] args)
{
String s =
"i like this program very much "
;
char
[] p = reverseWords(s.toCharArray());
System.out.print(p);
}
}
Python3
def
reverse_word(s, start, end):
while
start < end:
s[start], s[end]
=
s[end], s[start]
start
=
start
+
1
end
-
=
1
s
=
"i like this program very much"
s
=
list
(s)
start
=
0
while
True
:
try
:
end
=
s.index(
' '
, start)
reverse_word(s, start, end
-
1
)
start
=
end
+
1
except
ValueError:
reverse_word(s, start,
len
(s)
-
1
)
break
s.reverse()
s
=
"".join(s)
print
(s)
C#
using
System;
class
GFG {
static
void
reverse(
char
[] str,
int
start,
int
end)
{
char
temp;
while
(start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static
char
[] reverseWords(
char
[] s)
{
int
start = 0;
for
(
int
end = 0; end < s.Length; end++) {
if
(s[end] ==
' '
) {
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, start, s.Length - 1);
reverse(s, 0, s.Length - 1);
return
s;
}
public
static
void
Main(String[] args)
{
String s =
"i like this program very much "
;
char
[] p = reverseWords(s.ToCharArray());
Console.Write(p);
}
}
Javascript
<script>
function
reverse(str,start,end)
{
let temp;
while
(start <= end)
{
temp = str[start];
str[start]=str[end];
str[end]=temp;
start++;
end--;
}
}
function
reverseWords(s)
{
s=s.split(
""
);
let start = 0;
for
(let end = 0; end < s.length; end++)
{
if
(s[end] ==
' '
)
{
reverse(s, start, end);
start = end + 1;
}
}
reverse(s, start, s.length - 1);
reverse(s, 0, s.length - 1);
return
s.join(
""
);
}
var
s =
"i like this program very much "
;
document.write(reverseWords(s));
</script>
Output
much very program this like i
Time complexity: O(N)
Auxiliary Space: O(N)
Note: The above code doesn’t handle the cases when the string starts with space.
Below is the implementation of the approach that handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple spaces in between. Thanks to rka143 for providing this version.
C++
#include <bits/stdc++.h>
using
namespace
std;
void
reverse(string& s,
int
begin,
int
end)
{
while
(begin < end) {
swap(s[begin++], s[end--]);
}
}
void
reverseWords(string& s)
{
int
word_begin = -1;
int
i = 0;
while
(i < s.size()) {
if
((word_begin == -1) && (s[i] !=
' '
)) {
word_begin = i;
}
if
(word_begin != -1
&& ((s[i + 1] ==
' '
) || (i + 1 == s.size()))) {
reverse(s, word_begin, i);
word_begin = -1;
}
i++;
}
reverse(s, 0, s.size() - 1);
}
int
main()
{
string s =
"i like this program very much"
;
reverseWords(s);
cout << s << endl;
;
return
0;
}
C
#include <stdio.h>
void
reverse(
char
* begin,
char
* end)
{
char
temp;
while
(begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
void
reverseWords(
char
* s)
{
char
* word_begin = NULL;
char
* temp = s;
while
(*temp) {
if
((word_begin == NULL) && (*temp !=
' '
)) {
word_begin = temp;
}
if
(word_begin
&& ((*(temp + 1) ==
' '
)
|| (*(temp + 1) ==
''
))) {
reverse(word_begin, temp);
word_begin = NULL;
}
temp++;
}
reverse(s, temp - 1);
}
int
main()
{
char
s[] =
"i like this program very much"
;
char
* temp = s;
reverseWords(s);
printf
(
"%s"
, s);
return
0;
}
Java
import
java.io.*;
class
GFG {
static
void
reverse(
char
[] str,
int
start,
int
end)
{
char
temp;
while
(start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static
char
[] reverseWords(
char
[] s)
{
int
word_begin = -
1
;
int
i =
0
;
while
(i < s.length) {
if
((word_begin == -
1
) && (s[i] !=
' '
)) {
word_begin = i;
}
if
(word_begin != -
1
&& ((i +
1
== s.length)
|| (s[i +
1
] ==
' '
))) {
reverse(s, word_begin, i);
word_begin = -
1
;
}
i++;
}
reverse(s,
0
, (s.length -
1
));
return
s;
}
public
static
void
main(String[] args)
{
String s =
"i like this program very much"
;
char
[] p = reverseWords(s.toCharArray());
System.out.println(p);
}
}
Python3
def
reverse(
str
, start, end):
temp
=
''
str1
=
""
while
(start <
=
end):
temp
=
str
[start]
str
[start]
=
str
[end]
str
[end]
=
temp
start
+
=
1
end
-
=
1
return
str1.join(
str
)
def
reverseWords(s):
word_begin
=
-
1
i
=
0
while
(i <
len
(s)):
if
((word_begin
=
=
-
1
)
and
(s[i] !
=
' '
)):
word_begin
=
i
if
(word_begin !
=
-
1
and
((i
+
1
=
=
len
(s))
or
(s[i
+
1
]
=
=
' '
))):
s
=
reverse(
list
(s), word_begin, i)
word_begin
=
-
1
i
+
=
1
s
=
reverse(
list
(s),
0
, (
len
(s)
-
1
))
return
s
s
=
"i like this program very much"
p
=
reverseWords(
list
(s))
print
(p)
C#
using
System;
class
GFG
{
static
void
reverse(
char
[] str,
int
start,
int
end)
{
char
temp;
while
(start <= end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
static
char
[] reverseWords(
char
[] s)
{
int
word_begin = -1;
int
i = 0;
while
(i < s.Length) {
if
((word_begin == -1) && (s[i] !=
' '
)) {
word_begin = i;
}
if
(word_begin != -1
&& ((i + 1 == s.Length)
|| (s[i + 1] ==
' '
))) {
reverse(s, word_begin, i);
word_begin = -1;
}
i++;
}
reverse(s, 0, (s.Length - 1));
return
s;
}
static
void
Main(
string
[] args)
{
String s =
"i like this program very much"
;
char
[] p = reverseWords(s.ToCharArray());
Console.WriteLine(p);
}
}
Javascript
function
reverse(s, begin, end) {
while
(begin < end) {
let charArray = [...s];
let temp = charArray[begin];
charArray[begin] = charArray[end];
charArray[end] = temp;
begin++;
end--;
s = charArray.join(
""
);
}
return
s;
}
function
reverseWords(s) {
let word_begin = -1;
let i = 0;
while
(i < s.length) {
if
((word_begin == -1) && (s[i] !=
' '
)) {
word_begin = i;
}
if
(word_begin != -1
&& ((s[i + 1] ==
' '
) || (i + 1 == s.length))) {
s = reverse(s, word_begin, i);
word_begin = -1;
}
i++;
}
s = reverse(s, 0, s.length - 1);
return
s;
}
let s =
"i like this program very much"
;
s = reverseWords(s);
console.log(s);
Output
much very program this like i
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach: To solve the problem follow the below idea:
We can do the above task by splitting and saving the string in a reverse manner.
Follow the below steps to solve the problem:
- Store the string in the form of words
- Run a for loop in reverse order to print the words accordingly
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using
namespace
std;
int
main()
{
string s[] = {
"i"
,
"like"
,
"this"
,
"program"
,
"very"
,
"much"
};
string ans =
""
;
for
(
int
i = 5; i >= 0; i--) {
ans += s[i] +
" "
;
}
cout << (ans.substr(0, ans.length() - 1)) << endl;
return
0;
}
Java
public
class
ReverseWords {
public
static
void
main(String[] args)
{
String s[]
=
"i like this program very much"
.split(
" "
);
String ans =
""
;
for
(
int
i = s.length -
1
; i >=
0
; i--) {
ans += s[i] +
" "
;
}
System.out.println(
ans.substring(
0
, ans.length() -
1
));
}
}
Python3
s
=
"i like this program very much"
words
=
s.split(
' '
)
string
=
[]
for
word
in
words:
string.insert(
0
, word)
print
(
" "
.join(string))
C#
using
System;
public
class
ReverseWords {
public
static
void
Main()
{
string
[] s
=
"i like this program very much"
.Split(
' '
);
string
ans =
""
;
for
(
int
i = s.Length - 1; i >= 0; i--) {
ans += s[i] +
" "
;
}
Console.Write(ans.Substring(0, ans.Length - 1));
}
}
Javascript
<script>
var
s= [
"i"
,
"like"
,
"this"
,
"program"
,
"very"
,
"much"
];
var
ans =
""
;
for
(
var
i = 5; i >= 0; i--)
{
ans += s[i] +
" "
;
}
document.write(ans.slice(0,ans.length-1));
</script>
Output
much very program this like i
Time Complexity: O(N)
Auxiliary Space: O(N)
Reverse words in a given string using the swap operation:
The above task can also be accomplished by splitting the words separately and directly swapping the string starting from the middle.
Follow the below steps to solve the problem:
- Store the string in the form of words
- Swap the words with each other starting from the middle
- Print the string
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using
namespace
std;
string RevString(string s[],
int
l)
{
if
(l % 2 == 0) {
int
j = l / 2;
while
(j <= l - 1) {
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else
{
int
j = (l / 2) + 1;
while
(j <= l - 1) {
string temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
string S = s[0];
for
(
int
i = 1; i < 6; i++) {
S = S +
" "
+ s[i];
}
return
S;
}
int
main()
{
string s =
"i like this program very much"
;
string words[]
= {
"i"
,
"like"
,
"this"
,
"program"
,
"very"
,
"much"
};
cout << RevString(words, 6) << endl;
return
0;
}
Java
import
java.io.*;
class
GFG {
public
static
String[] RevString(String[] s,
int
l)
{
if
(l %
2
==
0
) {
int
j = l /
2
;
while
(j <= l -
1
) {
String temp;
temp = s[l - j -
1
];
s[l - j -
1
] = s[j];
s[j] = temp;
j +=
1
;
}
}
else
{
int
j = (l /
2
) +
1
;
while
(j <= l -
1
) {
String temp;
temp = s[l - j -
1
];
s[l - j -
1
] = s[j];
s[j] = temp;
j +=
1
;
}
}
return
s;
}
public
static
void
main(String[] args)
{
String s =
"i like this program very much"
;
String[] words = s.split(
"\s"
);
words = RevString(words, words.length);
s = String.join(
" "
, words);
System.out.println(s);
}
}
Python3
def
RevString(s, l):
if
l
%
2
=
=
0
:
j
=
int
(l
/
2
)
while
(j <
=
l
-
1
):
s[j], s[l
-
j
-
1
]
=
s[l
-
j
-
1
], s[j]
j
+
=
1
else
:
j
=
int
(l
/
2
+
1
)
while
(j <
=
l
-
1
):
s[j], s[l
-
1
-
j]
=
s[l
-
j
-
1
], s[j]
j
+
=
1
return
s
s
=
'i like this program very much '
string
=
s.split(
' '
)
string
=
RevString(string,
len
(string))
print
(
" "
.join(string))
C#
using
System;
class
GFG {
static
string
RevString(
string
[] s,
int
l)
{
if
(l % 2 == 0) {
int
j = l / 2;
while
(j <= l - 1) {
string
temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else
{
int
j = (l / 2) + 1;
while
(j <= l - 1) {
string
temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
string
S = s[0];
for
(
int
i = 1; i < 6; i++) {
S = S +
" "
+ s[i];
}
return
S;
}
public
static
void
Main()
{
string
[] words
= {
"i"
,
"like"
,
"this"
,
"program"
,
"very"
,
"much"
};
string
a = RevString(words, words.Length);
Console.WriteLine(a);
}
}
Javascript
<script>
function
RevString(s, l)
{
if
(l % 2 == 0)
{
let j = parseInt(l / 2, 10);
while
(j <= l - 1)
{
let temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
else
{
let j = parseInt((l / 2), 10) + 1;
while
(j <= l - 1)
{
let temp;
temp = s[l - j - 1];
s[l - j - 1] = s[j];
s[j] = temp;
j += 1;
}
}
let S = s[0];
for
(let i = 1; i < 9; i++)
{
S = S +
" "
+ s[i];
}
return
S;
}
let s =
"i like this program very much"
;
let words = [
"i"
,
"like"
,
"this"
,
"program"
,
"very much"
];
document.write(RevString(words, 9));
</script>
Output
much very program this like i
Time complexity: O(N)
Auxiliary Space: O(N)
Reverse words in a given string using constant space:
Follow the below steps to solve the problem:
- Go through the string and mirror each word in the string,
- Then, in the end, mirror the whole string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using
namespace
std;
string reverse_words(string s)
{
int
left = 0, i = 0, n = s.size();
while
(s[i] ==
' '
)
i++;
left = i;
while
(i < n) {
if
(i + 1 == n || s[i] ==
' '
) {
int
j = i - 1;
if
(i + 1 == n)
j++;
while
(left < j)
swap(s[left++], s[j--]);
left = i + 1;
}
if
(i > left && s[left] ==
' '
)
left = i;
i++;
}
reverse(s.begin(), s.end());
return
s;
}
int
main()
{
string str =
"i like this program very much"
;
str = reverse_words(str);
cout << str;
return
0;
}
Java
import
java.io.*;
class
GFG {
public
static
String swap(String str,
int
i,
int
j)
{
char
ch[] = str.toCharArray();
char
temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return
new
String(ch);
}
public
static
String reverse_words(String s)
{
int
left =
0
, i =
0
, n = s.length();
while
(s.charAt(i) ==
' '
)
i++;
left = i;
while
(i < n) {
if
(i +
1
== n || s.charAt(i) ==
' '
) {
int
j = i -
1
;
if
(i +
1
== n)
j++;
while
(left < j)
s = swap(s, left++, j--);
left = i +
1
;
}
if
(i > left && s.charAt(left) ==
' '
)
left = i;
i++;
}
s =
new
StringBuilder(s).reverse().toString();
return
s;
}
public
static
void
main(String[] args)
{
String str
=
"i like this program very much"
;
str = reverse_words(str);
System.out.println(str);
}
}
Python3
def
reverse_words(s):
left
=
0
i
=
0
s
=
list
(s)
n
=
len
(s)
while
(s[i]
=
=
' '
):
i
=
i
+
1
left
=
i
while
(i < n):
if
(i
+
1
=
=
n
or
s[i]
=
=
' '
):
j
=
i
-
1
if
i
+
1
=
=
n:
j
=
j
+
1
while
left < j:
s[left], s[j]
=
s[j], s[left]
left
=
left
+
1
j
=
j
-
1
left
=
i
+
1
if
(i > left
and
s[left]
=
=
' '
):
left
=
i
i
=
i
+
1
s
=
''.join(s)
s
=
s[::
-
1
]
return
s
s1
=
"i like this program very much"
s1
=
reverse_words(s1)
print
(s1)
C#
using
System;
class
GFG {
public
static
string
swap(
string
str,
int
i,
int
j)
{
char
[] ch = str.ToCharArray();
char
temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return
new
String(ch);
}
public
static
string
reverse_words(
string
s)
{
int
left = 0, i = 0, n = s.Length;
while
(s[i] ==
' '
)
i++;
left = i;
while
(i < n) {
if
(i + 1 == n || s[i] ==
' '
) {
int
j = i - 1;
if
(i + 1 == n)
j++;
while
(left < j)
s = swap(s, left++, j--);
left = i + 1;
}
if
(i > left && s[left] ==
' '
)
left = i;
i++;
}
char
[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return
new
string
(charArray);
}
public
static
void
Main(
string
[] args)
{
string
str =
"i like this program very much"
;
str = reverse_words(str);
Console.WriteLine(str);
}
}
Javascript
function
swap(s,a,b)
{
let charArray = [...s];
let temp = s[a];
charArray[a] = s[b];
charArray[b] = temp;
return
charArray.join(
""
);
}
function
reverse(str) {
let charArray = [...str];
let ans =
""
;
for
(let i=charArray.length-1;i>=0;i--)
{
ans+=charArray[i];
}
return
ans;
}
function
reverse_words(s)
{
let left = 0, i = 0, n = s.length;
while
(s[i] ==
' '
)
i++;
left = i;
while
(i < n) {
if
(i + 1 == n || s[i] ==
' '
) {
let j = i - 1;
if
(i + 1 == n)
j++;
while
(left < j)
{
s = swap(s,left++, j--);
}
left = i + 1;
}
if
(i > left && s[left] ==
' '
)
left = i;
i++;
}
s = reverse(s);
return
s;
}
let str =
"i like this program very much"
;
str = reverse_words(str);
console.log(str);
Output
much very program this like i
Time complexity: O(N)
Auxiliary Space: O(1)
Reverse words in a given string using constant space: using the slicing method and join functions:
Below is the implementation of the above approach:
Java
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
String text
=
"i like this program very much"
;
String str[] = text.split(
" "
);
Collections.reverse(Arrays.asList(str));
System.out.println(String.join(
" "
, str));
}
}
Python3
string
=
"i like this program very much"
s
=
string.split()[::
-
1
]
print
(
" "
.join(s))
PHP
<?php
$string
=
"i like this program very much"
;
$array
=
explode
(
" "
,
$string
);
$rarray
=
array_reverse
(
$array
);
echo
$newstring
= implode(
" "
,
$rarray
);
?>
C#
using
System;
using
System.Linq;
public
class
GFG {
static
public
void
Main()
{
string
text
=
"i like this program very much"
;
Console.WriteLine(
string
.Join(
" "
, text.Split(
' '
).Reverse()));
}
}
Javascript
let text=
"i like this program very much"
;
let str = text.split(
" "
);
str.reverse();
str = str.join(
" "
);
console.log(str);
C++
#include<bits/stdc++.h>
using
namespace
std;
int
main() {
string text =
"i like this program very much"
;
vector<string> str;
istringstream iss(text);
for
(string s; iss >> s;) {
str.push_back(s);
}
reverse(str.begin(), str.end());
cout << str[0];
for
(
int
i = 1; i < str.size(); i++) {
cout <<
" "
<< str[i];
}
return
0;
}
Output
much very program this like i
Time complexity: O(N2)
Auxiliary Space: O(N)
Approach: Without splitting the string
By this approach, we can even remove extra trailing spaces and in between the words also.
Basically, this algorithm involves 3 steps.
If you find white space, there can be two possibilities.
It might be end of a word or else extra trailing space in between the words.
if it is not a white space, add the character to temporary word as shown in the below code.
Java
import
java.util.*;
class
GFG {
public
static
String reverseString(String s)
{
StringBuilder ans=
new
StringBuilder();
String temp =
""
;
for
(
int
i=
0
;i<s.length();i++)
{
char
ch = s.charAt(i);
if
(ch==
' '
)
{
if
(!temp.equals(
""
))
{
ans.insert(
0
,temp+
" "
);
}
temp =
""
;
}
else
temp += ch;
}
return
ans.toString().substring(
0
,ans.length()-
1
);
}
public
static
void
main(String[] args) {
String s1=
" Welcome to Geeks For Geeks "
;
System.out.println(
"Before reversing length of string : "
+s1.length());
String ans1=reverseString(s1);
System.out.println(
"After reversing length of string : "
+ans1.length());
System.out.println(
"""
+ans1+
""n"
);
String s2=
" I Love Java Programming "
;
System.out.println(
"Before reversing length of string : "
+s2.length());
String ans2=reverseString(s2);
System.out.println(
"After reversing length of string : "
+ans2.length());
System.out.println(
"""
+ans2+
"""
);
}
}
Output
Before reversing length of string : 28 After reversing length of string : 26 "Geeks For Geeks to Welcome" Before reversing length of string : 28 After reversing length of string : 24 "Programming Java Love I"
Time Complexity: O(N) where N is length of string
Auxiliary Space: O(1)
Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.
I want to reverse each individual word of a String in Java (not the entire string, just each individual word).
Example: if input String is «Hello World» then the output should be «olleH dlroW».
asked Mar 14, 2010 at 7:32
0
This should do the trick. This will iterate through each word in the source string, reverse it using StringBuilder
‘s built-in reverse()
method, and output the reversed word.
String source = "Hello World";
for (String part : source.split(" ")) {
System.out.print(new StringBuilder(part).reverse().toString());
System.out.print(" ");
}
Output:
olleH dlroW
Notes: Commenters have correctly pointed out a few things that I thought I should mention here. This example will append an extra space to the end of the result. It also assumes your words are separated by a single space each and your sentence contains no punctuation.
answered Mar 14, 2010 at 7:43
William BrendelWilliam Brendel
31.6k14 gold badges71 silver badges77 bronze badges
10
Know your libraries
import org.apache.commons.lang.StringUtils;
String reverseWords(String sentence) {
return StringUtils.reverseDelimited(StringUtils.reverse(sentence), ' ');
}
answered Mar 14, 2010 at 13:03
JRLJRL
76.2k18 gold badges97 silver badges144 bronze badges
You need to do this on each word after you split
into an array
of words.
public String reverse(String word) {
char[] chs = word.toCharArray();
int i=0, j=chs.length-1;
while (i < j) {
// swap chs[i] and chs[j]
char t = chs[i];
chs[i] = chs[j];
chs[j] = t;
i++; j--;
}
return String.valueOf(chs);
}
xlm
6,53414 gold badges54 silver badges54 bronze badges
answered Mar 14, 2010 at 7:38
fastcodejavafastcodejava
39.4k28 gold badges131 silver badges185 bronze badges
1
Here’s the simplest solution that doesn’t even use any loops.
public class olleHdlroW {
static String reverse(String in, String out) {
return (in.isEmpty()) ? out :
(in.charAt(0) == ' ')
? out + ' ' + reverse(in.substring(1), "")
: reverse(in.substring(1), in.charAt(0) + out);
}
public static void main(String args[]) {
System.out.println(reverse("Hello World", ""));
}
}
Even if this is homework, feel free to copy it and submit it as your own. You’ll either get an extra credit (if you can explain how it works) or get caught for plagiarism (if you can’t).
answered Mar 14, 2010 at 8:05
9
No one here is considering unicode characters. You need to use java.text.BreakIterator
to find word boundaries and then use another one within each word boundary to enumerate character boundaries:
String helloWorld = "Heu0308llo World"; // Hëllo World
StringBuilder reverseStringBuilder = new StringBuilder(helloWorld.length());
BreakIterator wordBreakIterator = BreakIterator.getWordInstance();
wordBreakIterator.setText(helloWorld);
int wordStart = wordIterator.first();
int wordEnd = wordIterator.next();
while (wordEnd != BreakIterator.DONE) {
String word = helloWorld.substring(wordStart,wordEnd);
if (Character.isLetterOrDigit(word.charAt(0))) {
// "Hello" or "World" in our example
BreakIterator characterBreakIterator = BreakIterator.getCharacterInstance();
characterBreakIterator.setText(word);
int characterEnd = characterBreakIterator.last();
int characterStart = characterBreakIterator.previous();
while (characterStart != BreakIterator.DONE) {
reverseStringBuilder.append(word.substring(characterStart, characterEnd));
characterEnd = characterStart;
characterStart = characterBreakIterator.previous();
}
} else {
// " " in our example
reverseStringBuilder.append(word);
}
wordStart = wordEnd;
wordEnd = wordIterator.next();
}
String dlroWolleh = reverseStringBuilder.toString(); // "dlroW ollëH"
Using naive methods above will shift the diacritic character u0308
above the first l
when you reverse the String
. You want it to stay above the e
.
answered Nov 29, 2013 at 5:42
Heath BordersHeath Borders
30.6k16 gold badges142 silver badges253 bronze badges
1
Well I’m a C/C++ guy, practicing java for interviews let me know if something can be changed or bettered. The following allows for multiple spaces and newlines.
First one is using StringBuilder
public static String reverse(String str_words){
StringBuilder sb_result = new StringBuilder(str_words.length());
StringBuilder sb_tmp = new StringBuilder();
char c_tmp;
for(int i = 0; i < str_words.length(); i++){
c_tmp = str_words.charAt(i);
if(c_tmp == ' ' || c_tmp == 'n'){
if(sb_tmp.length() != 0){
sb_tmp.reverse();
sb_result.append(sb_tmp);
sb_tmp.setLength(0);
}
sb_result.append(c_tmp);
}else{
sb_tmp.append(c_tmp);
}
}
if(sb_tmp.length() != 0){
sb_tmp.reverse();
sb_result.append(sb_tmp);
}
return sb_result.toString();
}
This one is using char[]. I think its more efficient…
public static String reverse(String str_words){
char[] c_array = str_words.toCharArray();
int pos_start = 0;
int pos_end;
char c, c_tmp;
int i, j, rev_length;
for(i = 0; i < c_array.length; i++){
c = c_array[i];
if( c == ' ' || c == 'n'){
if(pos_start != i){
pos_end = i-1;
rev_length = (i-pos_start)/2;
for(j = 0; j < rev_length; j++){
c_tmp = c_array[pos_start+j];
c_array[pos_start+j] = c_array[pos_end-j];
c_array[pos_end-j] = c_tmp;
}
}
pos_start = i+1;
}
}
//redundant, if only java had '' @ end of string
if(pos_start != i){
pos_end = i-1;
rev_length = (i-pos_start)/2;
for(j = 0; j < rev_length; j++){
c_tmp = c_array[pos_start+j];
c_array[pos_start+j] = c_array[pos_end-j];
c_array[pos_end-j] = c_tmp;
}
}
return new String(c_array);
}
answered Aug 29, 2011 at 2:32
BaracsBaracs
511 silver badge3 bronze badges
0
I’m assuming you could just print the results (you just said ‘the output should be…’)
String str = "Hello World";
for (String word : str.split(" "))
reverse(word);
void reverse(String s) {
for (int idx = s.length() - 1; idx >= 0; idx--)
System.out.println(s.charAt(idx));
}
Or returning the reversed String:
String str = "Hello World";
StringBuilder reversed = new StringBuilder();
for (String word : str.split(" ")) {
reversed.append(reverse(word));
reversed.append(' ');
}
System.out.println(reversed);
String reverse(String s) {
StringBuilder b = new StringBuilder();
for (int idx = s.length() - 1; idx >= 0; idx--)
b.append(s.charAt(idx));
return b.toString();
}
Using only substring()
and recursion:
public String rev(String rest) {
if (rest.equals(""))
return "";
return rev(rest.substring(1)) + rest.substring(0,1);
}
answered Dec 14, 2013 at 0:21
dansalmodansalmo
11.4k5 gold badges57 silver badges52 bronze badges
2
Taking into account that the separator can be more than one space/tab and that we want to preserve them:
public static String reverse(String string)
{
StringBuilder sb = new StringBuilder(string.length());
StringBuilder wsb = new StringBuilder(string.length());
for (int i = 0; i < string.length(); i++)
{
char c = string.charAt(i);
if (c == 't' || c == ' ')
{
if (wsb.length() > 0)
{
sb.append(wsb.reverse().toString());
wsb = new StringBuilder(string.length() - sb.length());
}
sb.append(c);
}
else
{
wsb.append(c);
}
}
if (wsb.length() > 0)
{
sb.append(wsb.reverse().toString());
}
return sb.toString();
}
answered Mar 14, 2010 at 14:56
MikelMikel
4502 silver badges8 bronze badges
Heres a method that takes a string and reverses it.
public String reverse ( String s ) {
int length = s.length(), last = length - 1;
char[] chars = s.toCharArray();
for ( int i = 0; i < length/2; i++ ) {
char c = chars[i];
chars[i] = chars[last - i];
chars[last - i] = c;
}
return new String(chars);
}
First you need to split the string into words like this
String sample = "hello world";
String[] words = sample.split(" ");
answered Mar 14, 2010 at 7:41
ZakiZaki
6,9456 gold badges35 silver badges53 bronze badges
I came up with this answer while working on the problem. I tried not to use nested for loop solution O(N^2). I kind of forced myself to use stack for fun
public StringBuilder reverseWord(String input) {
char separator = ' ';
char[] chars = input.toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder sb = new StringBuilder(chars.length);
for(int i = 0; i < chars.length; i++) {
if(chars[i] != separator) { //letters
stack.push(chars[i]);
//if not last letter don't go any further
if(i != chars.length - 1) { continue; }
}
while(!stack.isEmpty()) {
sb.append(stack.pop());
}
sb.append(separator);
}
//remove the last separator
sb.deleteCharAt(sb.length() - 1);
return sb;
}
answered Jan 7, 2013 at 1:47
MeowMeow
18.1k52 gold badges135 silver badges179 bronze badges
1
public static void main(String[] args) {
System.out.println(eatWord(new StringBuilder("Hello World This Is Tony's Code"), new StringBuilder(), new StringBuilder()));
}
static StringBuilder eatWord(StringBuilder feed, StringBuilder swallowed, StringBuilder digested) {
for (int i = 0, size = feed.length(); i <= size; i++) {
if (feed.indexOf(" ") == 0 || feed.length() == 0) {
digested.append(swallowed + " ");
swallowed = new StringBuilder();
} else {
swallowed.insert(0, feed.charAt(0));
}
feed = (feed.length() > 0) ? feed.delete(0, 1) : feed ;
}
return digested;
}
run:
olleH dlroW sihT sI s'ynoT edoC
BUILD SUCCESSFUL (total time: 0 seconds)
answered Mar 14, 2010 at 7:46
SawyerSawyer
15.4k26 gold badges88 silver badges124 bronze badges
0
Using split(), you just have to change what you wish to split on.
public static String reverseString(String str)
{
String[] rstr;
String result = "";
int count = 0;
rstr = str.split(" ");
String words[] = new String[rstr.length];
for(int i = rstr.length-1; i >= 0; i--)
{
words[count] = rstr[i];
count++;
}
for(int j = 0; j <= words.length-1; j++)
{
result += words[j] + " ";
}
return result;
}
answered May 9, 2012 at 21:45
eweinewein
2,6756 gold badges36 silver badges54 bronze badges
1
String input = "Hello World!";
String temp = "";
String result = "";
for (int i = 0; i <= input.length(); i++) {
if (i != input.length() && input.charAt(i) != ' ') {
temp = input.charAt(i) + temp;
} else {
result = temp + " " + result;
temp = "";
}
}
System.out.println("the result is: " + result);
answered Mar 7, 2013 at 23:07
class ReverseWordsInString{
public static String reverse(String s1){
int l = s1.length();
if (l>1)
return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
else
return(s1.substring(0));
}
public static void main(String[] args){
String st = "Hello My World!";
String r = "";
for (String word : st.split(" "))
r += " "+ reverse(word);
System.out.println("Reversed words in the given string: "+r.trim());
}
}
answered Aug 15, 2013 at 22:16
dganesh2002dganesh2002
1,8471 gold badge26 silver badges28 bronze badges
3
Use split() function and reverse individual words
public String reverseSentence(String input)
{
String[] words = input.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : words)
{
String rev = " ";
for (int i = 0; i < s.length(); i++)
{
rev = s.charAt(i) + rev;
}
builder.append(rev);
}
return builder.toString().trim();
}
Remove the extra space that is added at the end of the new String using trim()
Output:
This is my sentence
sihT si ym ecnetnes
answered Dec 11, 2013 at 23:01
public String reverse(String arg) {
char[] s = arg.toCharArray();
StringBuilder sb = new StringBuilder();
boolean reverse = false;
boolean isChar = false;
int insertPos = 0;
for (int i = 0; i < s.length; i++) {
isChar = Character.isAlphabetic(s[i]);
if (!reverse && isChar) {
sb.append(s[i]);
insertPos = i;
reverse = true;
} else if (reverse && isChar) {
sb.insert(insertPos, s[i]);
} else if (!reverse && !isChar) {
sb.append(s[i]);
} else if (reverse && !isChar) {
reverse = false;
sb.append(s[i]);
}
}
return sb.toString();
}
answered Dec 16, 2013 at 0:54
0
package MujeebWorkspace.helps;
// javamujeeb@gmail.com
public class Mujeeb {
static String str= "This code is simple to reverse the word without changing positions";
static String[] reverse = str.split(" ");
public static void main(String [] args){
reverseMethod();
}
public static void reverseMethod(){
for (int k=0; k<=reverse.length-1; k++) {
String word =reverse[reverse.length-(reverse.length-k)];
String subword = (word+" ");
String [] splitsubword = subword.split("");
for (int i=subword.length(); i>0; i--){
System.out.print(splitsubword[i]);
}
}
}
}
Melquiades
8,5361 gold badge30 silver badges43 bronze badges
answered Dec 1, 2013 at 8:54
with and without api.
public class Reversal {
public static void main(String s[]){
String str= "hello world";
reversal(str);
}
static void reversal(String str){
String s[]=str.split(" ");
StringBuilder noapi=new StringBuilder();
StringBuilder api=new StringBuilder();
for(String r:s){
noapi.append(reversenoapi(r));
api.append(reverseapi(r));
}
System.out.println(noapi.toString());
System.out.println(api.toString());
}
static String reverseapi(String str){
StringBuilder sb=new StringBuilder();
sb.append(new StringBuilder(str).reverse().toString());
sb.append(' ');
return sb.toString();
}
static String reversenoapi(String str){
StringBuilder sb=new StringBuilder();
for(int i=str.length()-1;i>=0;i--){
sb.append(str.charAt(i));
}
sb.append(" ");
return sb.toString();
}
}
answered Aug 13, 2014 at 19:08
mathmath
1111 gold badge1 silver badge2 bronze badges
Reverse copy the string block-wise and then concatenate the whitespaces.
for eg. «hello java world».
1st block = «hello» reverse copy it:- «olleh» and add whitespace then
2nd block = «java» etc.
public static void main(String args[]) {
String s, rev = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
s = in.nextLine();
int length = s.length();
// char[] cs=s.toCharArray();
int l, r;
int i = 0;
while (i < length) {
l = i; // starting index
// find length of sub-block to reverse copy
while (i < length && s.charAt(i) != ' ') {
i++;
}
r = i - 1; // ending index
for (int j = r; j >= l; j--) { // copy reverse of sub-block
rev = rev + s.charAt(j);
}
rev = rev + " "; // add the whitespace
i++;
}
System.out.println("Reverse of entered string is: " + rev);
}
Program also works for multiple whitespaces between words.
answered Jun 16, 2015 at 23:23
GorvGoylGorvGoyl
40k27 gold badges216 silver badges211 bronze badges
Some of the above solutions are of the higher run time complexities. With the below algorithm, it can be achieved in O(n) time.
Algorithm:
- Parse the String from the end to beginning.
- Every time a space character is encountered i.e. » «, put the list of characters parsed till then in an ArrayList which can grow dynamically.
- Print the ArrayList in the reverse order which gives you the desired output.
Complexity: O(n) where n is the length of the String.
import java.io.IOException;
import java.util.ArrayList;
public class WordReverse {
public static void main(String[] args) throws IOException {
String inputStr = "Hello World";
String reversed = "";
ArrayList<String> alist = new ArrayList<String>();
for (int i = inputStr.length() - 1; i >= 0; i--) {
if (inputStr.charAt(i) != ' ') {
reversed = reversed + inputStr.charAt(i);
} else {
alist.add(reversed);
reversed = "";
}
}
alist.add(reversed);
String result = "";
for (int i = alist.size() - 1; i >= 0; i--) {
result = result + alist.get(i);
result = result + " ";
}
System.out.println(result);
}
}
answered Dec 27, 2015 at 8:04
VamsiVamsi
286 bronze badges
Solution with TC — O(n) and SC — O(1)
public String reverseString(String str){
String str = "Hello Wrold";
int start = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ' || i == str.length() - 1) {
int end = 0;
if (i == str.length() - 1) {
end = i;
} else {
end = i - 1;
}
str = swap(str, start, end);
start = i + 1;
}
}
System.out.println(str);
}
private static String swap(String str, int start, int end) {
StringBuilder sb = new StringBuilder(str);
while (start < end) {
sb.setCharAt(start, str.charAt(end));
sb.setCharAt(end, str.charAt(start));
start++;
end--;
}
return sb.toString();
}
answered Apr 2, 2020 at 5:45
AbhayAbhay
1291 silver badge5 bronze badges
example with stream API
public static String reverseAllWords(String str) {
String[] arr = str.split(" ");
String res = "";
for (int x = 0; x < arr.length; x++) {
res = res + Stream.of(arr[x].split("")).reduce("", (a, b) -> b + a) + " ";
}
return res;
}
answered Apr 26, 2020 at 21:01
Shell ScottShell Scott
1,62918 silver badges27 bronze badges
You can reverse a string using the enhanced for loop and swap the summands inside:
public static String reverse(String str) {
String revStr = "";
for (char ch : str.toCharArray()) {
// concat of chars in reverse order
revStr = ch + revStr;
}
return revStr;
}
public static String[] reverse(String[] arr) {
String[] revArr = new String[arr.length];
for (int i = 0; i < arr.length; i++) {
// same word order
revArr[i] = reverse(arr[i]);
}
return revArr;
}
public static void main(String[] args) {
String[] arr = reverse("Hello World".split(" "));
System.out.println(String.join(" ", arr));
}
Output:
olleH dlroW
answered Mar 27, 2021 at 11:49
String someString = new String("Love thy neighbor");
System.out.println(someString);
char[] someChar = someString.toCharArray();
int j = someChar.length - 1;
char temp;
for (int i = 0; i <= someChar.length / 2; i++) {
temp = someChar[i];
someChar[i] = someChar[j];
someChar[j] = temp;
j--;
}
someString = new String(someChar);
System.out.println(someString);
Run:
Love thy neighbor
robhgien yht evoL
answered Mar 6, 2013 at 4:08
1
This reverses the words in the given string. Words are assumed to be separated by a single space. Reversal is done in place (in the character buffer).
public static String reversePhrases(String s)
{
char[] buf = s.toCharArray();
int len = buf.length;
int start = 0;
for (int i = 0; i < len; i++) {
if (buf[i] == ' ' || i == (len-1)) {
if (i == (len-1)) {
i = len;
}
int end = (start + i)/2;
for (int j = start; j < end; j++) {
char c = buf[j];
int pos = (start + i) - j - 1;
buf[j] = buf[pos];
buf[pos] = c;
}
start = i + 1;
}
}
return new String(buf);
}
animuson♦
53.5k28 gold badges142 silver badges147 bronze badges
answered Jul 4, 2013 at 15:29
0
Easy way:
String reverseString(String string)
{
String newString = "";
for(int x = string.length() - 1; x > -1; x ++)
newString += string.charAt(x);
return newString;
}
answered Jul 28, 2013 at 20:10
Back to: C#.NET Programs and Algorithms
In this article, I am going to discuss How to Reverse Each Word in a Given String in C# with some examples. Please read our previous article where we discussed How to Reverse a String in C# program with some examples. As part of this article, we are going to use the following three approaches to reverse each word in a given string C#.
- Without using a built-in function
- Using Stack
- Using LINQ
Program Description:
The user will input a string and we need to reverse each word individually without changing its position in the string. Here, we will take the input as a string from the user and then we need to reverse each word individually without changing their position in the sentence as shown in the below image.
Method1: Without using any built-in function:
In the following example, we generate all words separated by space. Then reverse the words one by one.
using System; using System.Collections.Generic; using System.Text; namespace LogicalPrograms { class Program { static void Main(string[] args) { Console.Write("Enter a String : "); string originalString = Console.ReadLine(); StringBuilder reverseWordString = new StringBuilder(); List<char> charlist = new List<char>(); for (int i = 0; i < originalString.Length; i++) { if (originalString[i] == ' ' || i == originalString.Length - 1) { if (i == originalString.Length - 1) charlist.Add(originalString[i]); for (int j = charlist.Count - 1; j >= 0; j--) reverseWordString.Append(charlist[j]); reverseWordString.Append(' '); charlist = new List<char>(); } else { charlist.Add(originalString[i]); } } Console.WriteLine($"Reverse Word String : {reverseWordString.ToString()}"); Console.ReadKey(); } } }
Output:
Method2: Using Stack to Reverse Each Word in C#
Here, we are using a stack to push all words before space. Then as soon as we encounter a space, we empty the stack. The program is self-explained, so please go through the comments line.
using System; using System.Collections.Generic; namespace LogicalPrograms { class Program { static void Main(string[] args) { Console.Write("Enter a String : "); string originalString = Console.ReadLine(); Stack<char> charStack = new Stack<char>(); // Traverse the given string and push all characters // to stack until we see a space. for (int i = 0; i < originalString.Length; ++i) { if (originalString[i] != ' ') { charStack.Push(originalString[i]); } // When seeing a space, then print contents of the stack. else { while (charStack.Count > 0) { Console.Write(charStack.Pop()); } Console.Write(" "); } } // Since there may not be space after last word. while (charStack.Count > 0) { Console.Write(charStack.Pop()); } Console.ReadKey(); } } }
Method3: Using Linq to Reverse Each Word in C#
using System; using System.Linq; namespace LogicalPrograms { class Program { static void Main(string[] args) { Console.Write("Enter a String : "); string originalString = Console.ReadLine(); string reverseWordString = string.Join(" ", originalString .Split(' ') .Select(x => new String(x.Reverse().ToArray()))); Console.WriteLine($"Reverse Word String : {reverseWordString}"); Console.ReadKey(); } } }
Output:
Code Explanation:
Split the input string using a single space as the separator.
The Split method is used for returning a string array that contains each word of the input string. We use the Select method for constructing a new string array, by reversing each character in each word. Finally, we use the Join method for converting the string array into a string.
In the next article, I am going to discuss How to Remove Duplicate Characters from a given string in C# using different mechanisms. I hope now you understood How to Reverse Each Word in a Given String in C# with different mechanisms.
We will develop a program to reverse each word in a string python. In this article, we are using the split() function, list comprehension, and join() function to reverse each word of a string in Python. The split() method splits the string from the specified separator and returns a list object with string elements. The join() method takes all items in an iterable and joins them into one string. A string must be specified as the separator. List comprehensions provide a concise way to create lists.
Example of reverse each word in a string:-
String: know program is best to learn programming
Reverse: wonk margorp si tseb ot nrael gnimmargorp
We will take a string while declaring the variables. Then, find the reverse of each word in a string using the for loop. Finally, the result will be displayed on the screen.
# Python program to reverse each word in a string
# take inputs
string = 'Know Program'
# splitting the string into list of words
words = string.split(' ')
# reversing each word and creating a new list of words
reverseWords = [word[::-1] for word in words]
# joining the new list of words to for a new string
reverseString = " ".join(reverseWords)
# print reverse of each word in a string
print('The reverse is', reverseString)
Output:-
The reverse is wonK margorP
Python Program to Reverse Each Word in a String
In the previous program, inputs are hardcoded in the program but in this program, input will be provided by the user.
# Python program to reverse each word in a string
# take inputs
string = input('Enter the string: ')
# splitting the string into list of words
words = string.split(' ')
# reversing each word and creating a new list of words
reverseWords = [word[::-1] for word in words]
# joining the new list of words to for a new string
reverseString = " ".join(reverseWords)
# print reverse of each word in a string
print('The reverse is', reverseString)
Output for the input values test-case-1:-
Enter the string: Welcome to Know Program
The reverse is emocleW ot wonK margorP
Output for the input values test-case-2:-
Enter the string: reverse each word in a string python
The reverse is esrever hcae drow ni a gnirts nohtyp
Reversing Each Word in a String in Python
This method is similar to the above method, but rather a shorthand method. In this program, reverse each word of the string in one line.
# Python program to reverse each word in a string
# take inputs
string = input('Enter the string: ')
# reverse each word in a string
reverseString = " ".join(word[::-1] for word in string.split(" "))
# print reverse of each word in a string
print('The reverse is', reverseString)
Output:-
Enter the string: Python Program
The reverse is nohtyP margorP
Reverse Each Word in a String Python
We can also take the help of a function to reverse each word in a string. A function is a block of code that performs a specific task.
# Python program to reverse each word in a string
def reverseWords(s): #user-defined function
return " ".join(word[::-1] for word in s.split(" "))
# take inputs
string = input('Enter the string: ')
# calling function and display result
print('The reverse is', reverseWords(string))
Output for the input values test-case-1:-
Enter the string: My name is guddu kumar singh
The reverse is yM eman si uddug ramuk hgnis
Output for the input values test-case-2:-
Enter the string: know program is best to learn programming
The reverse is wonk margorp si tseb ot nrael gnimmargorp
Also See:- Python Program to Reverse a String
Given a string reverse each words in it.
Example
Input: "the sky is blue" Output: "blue is sky the" Input: " hello world! " Output: "world! hello" Explanation: Reversed string should not contain leading or trailing spaces.
There are multiple ways through which this problem can be solved, but we will categorize it in two parts.
1. Using extra space.
2. Using constant space.
Reverse words in a string using constant space.
Conceptually this is how it works
- Use two variables to track the white spaces on both the ends.
- Then iterate the string without the trailing spaces and keep adding each character to form a word. If we encounter a empty space then add the formed word to the final result and reset the word.
- Keep doing this for each character in the string.
- In the end after the iteration if there is character in the word then add that to the result.
const reverseWords = (s) => { let left = 0; let right = s.length-1; //remove the trailing spaces from both end while (s[left] === " ") left++; while (s[right] === " ") right--; let word = ""; let result = ""; //Iterate the string and keep on adding to form a word //If empty space is encountered then add the formed word to the result while (left <= right) { const char = s[left]; if (char !== " ") { word += char; } else if (word && char === " ") { if (result) result = word + " " + result; else result = word; word = ""; } left++; } //If not empty string then add to the result if (word) { if (result) result = word + " " + result; else result = word; } return result; }
Input: console.log(reverseWords("learnersbucket practice code")); Output: "code practice learnersbucket"
Time complexity: O(n).
Space complexity: O(4).
Reverse words in a string by utilizing extra space.
Basically in this approach we break the string in the array of words and then reverse the array and join it again to form the string.
There are multiple ways to do that.
Method 1: Using stack.
const reverseWords = (s) => { //Split into array of words const words = s.split(' '); //Use stack to reverse the words const stack = []; //Add each from array to the stack for(let i of words) { stack.push(i); } let fS = ""; //Get each word from stack and form the reversed string while(stack.length) { const cS = stack.pop(); if(cS) { fS += " " + cS; } } //Return the string return fS.trim(); };
Method 2: Simply iterating the words array in reverse direction
const reverseWords = (str) => { const words = str.split(" "); let ans = ""; for(let i = words.length - 1; i >= 0; i--){ ans = `${ans} ${words[i]}`; } return ans.trim(); }
Method 3: Filtering the empty space from the array of words so that we don’t have to trim it at the end.
const reverseWords = (s) => { return s.split(" ").filter(Boolean).reverse().join(" "); };
Method 4: Properly splitting the string on each word.
const reverseWords = s => s.trim().split(/s+/).reverse().join(' ');
For each of these methods
Time complexity: O(n).
Space complexity: O(n).
A quick and practical program to reverse only words in a given string. Example programs using StringBuilder and java 8 streams with splitAsStream(), map(), Collectors.joining() methods.
1. Overview
In this tutorial, We’ll learn how to reverse the words in a string in java. The solution to this problem can be done using the StringBuilder class and using java 8 stream concepts. Many developers will be confused about whether word order needs to be reversed or each word should be reversed. You should clear on this with the interviewer. This will give a hint to the interviewer that the candidate is thinking and coming with a questionnaire.
But in this article, we will be reversing each word as it appears the order in the input as below.
Example:
String input = "Welcome to the JavaProgramTo.com blog"
emocleW ot eht moc.oTmargorPavaJ golb
We recommend trying to solve the problem without seeing the answers. Once you come up with your own algorithm then see the different answers.
2. Using StringBuilder and String split() method
In this approach, we will be using the String split(), charAt(), length() and StringBuilder class append append() methods.
A) First split the given string by whitespace.
B) Take the first word and reverse it. Finally, add the reversed word to the new StringBuilder. Append the white space at the end of each word.
C) Repeat step B for all words.
D) Finally, covert StringBuilder into String using the toString() method.
package com.java.w3schools.blog.java.program.to.strings; /** * * Reversing each word in string without loosing its initial order of the words. * * @author javaprogramto.com * */ public class ReverseWordsStringBuilder { private static final String WHITESPACE_DELIMITER = " "; public static void main(String[] args) { System.out.println("Examples to reversing each word in a string inplace."); String input1 = "Welcome to the JavaProgramTo.com blog"; String output1 = reverseWordsWithStringBuilder(input1); System.out.println(" input 1 : " + input1); System.out.println(" output 1 : " + output1); String input2 = "This is part of String interview programs"; String output2 = reverseWordsWithStringBuilder(input2); System.out.println(" input 2 : " + input2); System.out.println(" output 2 : " + output2); } public static String reverseWordsWithStringBuilder(String input) { StringBuilder reversedFinalOutput = new StringBuilder(); // splitting the input string by space. String[] words = input.split(WHITESPACE_DELIMITER); for (String word : words) { StringBuilder reversedWord = new StringBuilder(); for (int i = word.length() - 1; i >= 0; i--) { reversedWord.append(word.charAt(i)); } reversedFinalOutput.append(reversedWord).append(WHITESPACE_DELIMITER); // to clear the builder obj. //reversedWord.setLength(0); } String finalOutputStr = reversedFinalOutput.toString(); return finalOutputStr; } }
Output:
Examples to reversing each word in a string inplace. input 1 : Welcome to the JavaProgramTo.com blog output 1 : emocleW ot eht moc.oTmargorPavaJ golb input 2 : This is part of String interview programs output 2 : sihT si trap fo gnirtS weivretni smargorp
3. Using Java 8 Functional Programming
Java 8 Stream api have come up with the new methods that follow functional programming. Now, let us see how we can reverse each word in the string without changing the order of the words.
Pattern class introduced with a stream method splitAsStream() which returns a Stream of Strings. Next, use the map() method to do reverse the string using StringBuilder.reverse() method. Finally, invoke the Collectors.joining(» «) which will collect all strings from the map() method and concatenate them with empty space » » by each word.
Java 8 map() examples
Let us take a look at the Java 8 example program.
First, need to create a Pattern instance to identify the empty space using a regular expression.
This has mainly three steps.
A) Converting input string into the stream.
B) Reversing each word.
C) Merging all reversed words with empty space » «
package com.java.w3schools.blog.java.program.to.strings; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * * Reversing each word in string without loosing its initial order of the words * using java 8 stream with functional style. * * @author javaprogramto.com * */ public class ReverseWordsJava8Streams { // pattern matches to the given delimiter (" ") private static final Pattern pattern = Pattern.compile(" +"); public static void main(String[] args) { System.out.println("Java 8 program : "); String input1 = "java pattern and stream api"; String output1 = reverseWordsWithStringBuilder(input1); System.out.println(" output 1 : " + output1); String input2 = "reversing using java 8 streams"; String output2 = reverseWordsWithStringBuilder(input2); System.out.println(" output 2 : " + output2); } public static String reverseWordsWithStringBuilder(String input) { // step 1: converting input string into stream. Stream<String> stream = pattern.splitAsStream(input); // step 2: reversing each word. Stream<StringBuilder> intermeidateOutput = stream.map(word -> new StringBuilder(word).reverse()); // step 3: merging all reversed words with empty space " " String reversedInput = intermeidateOutput.collect(Collectors.joining(" ")); return reversedInput; } }
Output:
Java 8 program : output 1 : avaj nrettap dna maerts ipa output 2 : gnisrever gnisu avaj 8 smaerts
4. Possible Exceptions/Errors:
Here are the problems that come across the implementation. These would be useful when you are trying on your own first and not looking at the solutions.
Examples to reversing each word in a string inplace. Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:702) at com.java.w3schools.blog.java.program.to.strings.ReverseWordsStringBuilder.reverseWordsWithStringBuilder(ReverseWordsStringBuilder.java:39) at com.java.w3schools.blog.java.program.to.strings.ReverseWordsStringBuilder.main(ReverseWordsStringBuilder.java:18)
5. Conclusion
In this article, We’ve seen how to reverse each word in a string. Example programs are shown using traditional and java 8 functional style programming model.
And also shown the problems faced during the implementation of the programs.
We can easily reverse words in a string in JavaScript using the JavaScript split(), reverse() and join() methods. Below is a function we will create to reverse words in a string.
function reverseWords(str){
var newString = str.split(" ");
newString.reverse();
newString = newString.join(" ");
return newString;
};
Here is the function in use with an example string:
function reverseWords(str){
var newString = str.split(" ");
newString.reverse();
newString = newString.join(" ");
return newString;
};
var someString = "This is an example string with words";
console.log(reverseWords(someString));
#Output:
words with string example an is This
When using string variables in JavaScript, we can easily perform string manipulation to change the values or order of the words in our string.
One such manipulation is to reverse the words in a string.
To reverse the words in a string, we can first use the split() method to get an array of each word in the string, and then use the reverse() method to return the array with all of the items in reverse.
After reversing the array we then join the words together using the JavaScript join() method.
Below is our function once again on how to reverse the words in a string using JavaScript.
function reverseWords(str){
var newString = str.split(" ");
newString.reverse();
newString = newString.join(" ");
return newString;
};
Reversing Each Word in a String Using JavaScript
If you are looking to reverse each word in a string, we can modify our examples from above slightly. Instead of reversing the order of the words, we will reverse the letters of each word.
In this case, we will split() the string to get each word, and then loop over each word and reverse it with string slicing.
We have a post on reversing a string, it basically uses the same idea as our function above.
Below is an example of how to reverse each word in a string with JavaScript.
function reverseEachWord(str){
var newStringArr = str.split(" ");
for ( var i=0; i<newStringArr.length; i++){
newStringArr[i] = newStringArr[i].split("");
newStringArr[i].reverse();
newStringArr[i] = newStringArr[i].join("");
}
newStringArr = newStringArr.join(" ");
return newStringArr;
};
And here is the function in use with an example string:
function reverseEachWord(str){
var newStringArr = str.split(" ");
for ( var i=0; i<newStringArr.length; i++){
newStringArr[i] = newStringArr[i].split("");
newStringArr[i].reverse();
newStringArr[i] = newStringArr[i].join("");
}
newStringArr = newStringArr.join(" ");
return newStringArr;
};
var someString = "This is an example string with words";
console.log(reverseEachWord(someString));
#Output:
sihT si na elpmaxe gnirts htiw sdrow
Hopefully this article has been helpful for you to learn how to reverse words in a string using JavaScript.
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
In these java programs, learn to reverse the words of a string in Java without using api functions.
We can reverse the words of string in two ways:
- Reverse each word’s characters but the position of word in string remain unchanged.
Original string : how to do in java Reversed string : woh ot od ni avaj
- Reverse the string word by word but each word’s characters remain unchanged.
Original string : how to do in java Reversed string : java in do to how
1. Reverse each word’s characters in string
In this example, we will follow below steps to reverse the characters of each word in it’s place.
Read string from input.
Split the string by using space as delimiter.
Loop through all words.
– Reverse the characters of each word.
Print the final string.
package com.howtodoinjava.example; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Original string : "); String originalStr = scanner.nextLine(); scanner.close(); String words[] = originalStr.split("\s"); String reversedString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length() - 1; j >= 0; j--) { reverseWord = reverseWord + word.charAt(j); } reversedString = reversedString + reverseWord + " "; } // Displaying the string after reverse System.out.print("Reversed string : " + reversedString); } }
Program output.
Original string : I love java programming Reversed string : I evol avaj gnimmargorp
In this java program, we will reverse the string in such a way that each word’s characters are unchanged – but words are reversed in string by their position in the string.
package com.howtodoinjava.example; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Original string : "); String originalStr = scanner.nextLine(); scanner.close(); String words[] = originalStr.split("\s"); String reversedString = ""; //Reverse each word's position for (int i = 0; i < words.length; i++) { if (i == words.length - 1) reversedString = words[i] + reversedString; else reversedString = " " + words[i] + reversedString; } // Displaying the string after reverse System.out.print("Reversed string : " + reversedString); } }
Program output.
Original string : I love java programming Reversed string : programming java love I
Drop me your questions related to reverse each words in a string or reverse a sentence without using functions in Java.
Happy Learning !!
- Problem Statement
- Sample Test Cases
- Approach
- Naive Approach
- C++ Code
- Java Code
- Python Code
- Optimal Approach
- C++ Code
- Java Code
- Python Code
- FAQs
Problem Statement
Given a sentence of the form of words separated by spaces, return a new sentence that consists of the words of the original sentence in the reverse order.
Sample Test Cases
Input 1:
s = “Hello World”
Confused about your next job?
In 3 simple steps you can find your personalised career roadmap in Software development for FREE
Expand in New Tab
Output 1:
World Hello
Input 2:
s = “This is a good day”
Output 2:
day good a is This
Approach
Naive Approach
The naive approach for this problem is to split the string into individual words using the spaces as delimiters, and then print the words in reverse order.
Code / Implementation:
C++ Code
string reverseStringByWords(string s) { vector < string > words; string word = ""; for (char c: s) { if (c == ' ') { words.push_back(word); word = ""; } else { word += c; } } words.push_back(word); string ans = ""; reverse(words.begin(), words.end()); for (auto x: words) { ans += x; ans += " "; } return ans; }
Java Code
public static void reverse(char[] ch, int left, int right) { while (left <= right) { char temp = ch[right]; ch[right] = ch[left]; ch[left] = temp; left++; right--; } } public static String reverseByWords(String s) { char[] ch = s.toCharArray(); int beg = 0; for (int i = 0; i < ch.length; i++) { if (ch[i] == ' ') { reverse(ch, beg, i); beg = i + 1; } } reverse(ch, beg, ch.length - 1); reverse(ch, 0, ch.length - 1); String ans = Arrays.toString(ch); return ans; }
Python Code
def reverse(s, left, right): while left <= right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 def reverseByWords(s): s = list(s) n = len(s) beg = 0 for i in range(n): if s[i] == " ": reverse(s, beg, i - 1) beg = i + 1 reverse(s, beg, n - 1) reverse(s, 0, n - 1) s = "".join(s) return s
Complexity Analysis:
- Time Complexity: O(n)
- Space Complexity: O(n)
Optimal Approach
The optimal approach tries to swap the words of the string from the beginning and end, using a two-pointers-based approach, to reverse the string in constant space. The algorithm is as follows:
- Convert the string into an array of strings, which will store the words.
- Initialize the 2 pointers left and right to 0 and string.length() – 1 respectively.
- While the left pointer does not exceed the right pointer, swap the elements at the left and right pointer, move the left pointer forward and the right pointer backward by 1 place.
- Finally, return the final calculated string.
Implementation:
C++ Code
string reverseByWords(string s) { vector < string > words; string str = ""; for (char c: s) { if (c == ' ') { words.push_back(str); str = ""; } else { str += c; } } words.push_back(str); int left = 0, right = words.size() - 1; while (left <= right) { swap(words[left], words[right]); left++; right--; } string ans = ""; for (auto x: words) { ans += x; ans += " "; } ans.pop_back(); return ans; }
Java Code
public static String reverseByWords(String s) { String[] words = s.split("\s"); int left = 0, right = words.length - 1; while (left <= right) { String temp = words[left]; words[left] = words[right]; words[right] = temp; left += 1; right -= 1; } String ans = String.join(" ", words); return ans; }
Python Code
def reverseByWords(s): s = s.split(" ") left = 0 right = len(s) - 1 while left <= right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 s = " ".join(s) return s
Complexity Analysis:
- Time Complexity: O(n)
- Space Complexity: O(1)
Practice Problem:
Reverse the String
FAQs
1. When a problem is asked to be solved in constant space, what should be the thought process?
A. While the idea may vary from problem to problem, swapping is a very common method used in problems requiring to be solved in constant space.
2. What is the time complexity of the swap function in C++?
A. The swap function in C++ works in O(1) time complexity.