Program to Reverse words in a sentence (Java , C and Python)
The goal of this program is reverse words in a sentence
for eg : Original string: Neil Peart rocks YYZ
we need : YYZ rocks Peart Neil
To make life simple let us see two programs that use simple strategy of splitting the sentences based on delimiters in this case spaces ” ” and then append the splits to a buffer or a stack
The first strategy is to use a stack and implemented in Java
import java.util.*;
public class StringReverseWord
{
public static void main(String[] args) {
String a = "Neil Peart rocks YYZ";
Stack <String> stack = new Stack <String>();
String[] temp;
String delimiter = " ";
// given string will be split by the argument delimiter provided.
temp = a.split(delimiter);
// push substring to stack
for(int i =0; i < temp.length ; i++)
{
stack.push(temp[i]);
}
System.out.println("\nOriginal string: " + a);
System.out.print("Reverse word string: ");
while(!stack.empty()) {
System.out.print(stack.pop());
System.out.print(" ");
}
System.out.println("\n");
}
}
OUTPUT:
laptop:~/code$ java StringReverseWord
Original string: Neil Peart rocks YYZ
Reverse word string: YYZ rocks Peart Neil
Below is a Java implementation using an additional buffer with same strategy of splitting based on a space delimiter
import java.io.*;
public class ReverseWords
{
public static void main(String[] args) {
String s = "Neil Peart rocks YYZ";
String[] str =s.split(" ");
StringBuffer buffer = new StringBuffer();
for(int i=str.length-1;i>=0;i--)
{
buffer.append(str[i]);
buffer.append(" ");
}
System.out.println("\nOriginal string: " + s);
System.out.println("Reverse word string:"+buffer.toString());
}
}
OUTPUT:
laptop:~/code$ java ReverseWords
Original string: Neil Peart rocks YYZ
Reverse word string:YYZ rocks Peart Neil
The Below program is implemented in C and uses a strategy of reversing individual words initially and then reversing this resultant string.
#include<stdio.h>
/* function to reverse a string */
void reverse(char *start, char *end);
/*Function to reverse words*/
void reversewords(char *s)
{
char *word = s;
char *temp = s;
/*start reversing the individual words*/
while( *temp )
{
temp++;
if (*temp == '\0')
{
reverse(word, temp-1);
}
else if(*temp == ' ')
{
reverse(word, temp-1);
word = temp+1;
}
}
reverse(s, temp-1);/*Reverse the resultant string from beginning to end including spaces*/
}
/*Function to reverse a string this is similar to earlier blog post to reverse a string */
void reverse(char *start, char *end)
{
char temp;
while (start < end)
{
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
int main()
{
char s[] = "Neil Peart rocks YYZ";
char *temp = s;
printf("Original string: %s\n",s);
reversewords(s);
printf("Reverse word string: %s\n", s);
return 0;
}
OUTPUT:
laptop:~/code$ ./a.out
Original string: Neil Peart rocks YYZ
Reverse word string: YYZ rocks Peart Neil
For python coders
laptop:~/code$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> string = "Neil Peart rocks YYZ" >>> " ".join(string.split()[::-1]) 'YYZ rocks Peart Neil'
The code in this article is to illustrate the approach taken to solve this usual problem and does not cover all test cases. Keep posting your fail proof versions in the comments.

import java.util.Stack; public class SentenceRevrese2 { public static void main(String[] args) { String a = "This is Channel Mentor"; String[] temp; String delimiter =" "; temp = a.split(delimiter); String re=""; for(int i =0; i < temp.length ; i++) { String var1=(temp[i])!=null?temp[i]:""; re=var1+" "+re; } System.out.println(re);} }import java.util.*;
public class UsingStack {
public static void main(String[] Args){
String sentence = “This is to reverse a sentence”;
Stack stack = new Stack();
String[] rev;
int i=0;
rev = sentence.split(” “);
for(i=0;i<rev.length;i++){
stack.push(rev[i]);
}
for(i=0;i<rev.length;i++){
System.out.println(stack.pop());
}
}
}
can you please give sample code to reverse the sentence without using any function like split or any other function
// .Net without built-in functions
string newStr = “”;
int lastChar = input.Length;
for (int i = input.Length – 1; i >= 0; i–)
{
if (input[i] == ‘ ‘ || i == 0)
{
for (int j = (i == 0 ? 0 : i + 1); j < lastChar; j++)
{
newStr += input[j];
}
newStr += (i == 0 ? "" : " ");
lastChar = i;
}
}
return newStr;
static void Main(string[] args)
{
string str = “I am qudsia”;
int prev = str.Length , index ;
for (int i = str.Length- 1; i > 0; i–)
{
index = str.IndexOf(” “, i);
if (i == index)
{
Console.Write(str.Substring(i+1, prev -i -1));
Console.Write(” “);
prev = i;
}
}
Console.Write(str.Substring(0, prev));
}
This is an very easy version of this program which i created! Hope this helps new biezzz
static void Main(string[] args)
{
string str = "I am qudsia";
int prev = str.Length , index ;
for (int i = str.Length- 1; i > 0; i--)
{
index = str.IndexOf(" ", i);
if (i == index)
{
Console.Write(str.Substring(i+1, prev -i -1));
Console.Write(" ");
prev = i;
}
}
Console.Write(str.Substring(0, prev));
Console.Read();
}
Your C code fails. Try a leading blank and 2 trailing blanks: ” This is a test “