Skip to content

Program to Reverse words in a sentence (Java , C and Python)

January 19, 2011

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.

About these ads

From → Algorithms, Strings

8 Comments
  1. krishna permalink
    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);}
    }
    
  2. Sandeep permalink

    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());
    }
    }
    }

  3. ankit permalink

    can you please give sample code to reverse the sentence without using any function like split or any other function

  4. // .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;

  5. Qudsia Meher permalink

    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

  6. Qudsia Meher permalink


    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();
    }

  7. Bilbo Baggins permalink

    Your C code fails. Try a leading blank and 2 trailing blanks: ” This is a test “

  8. niraj permalink

    package niraj_pract;
    import java.util.Scanner;

    public class reverse {
    public static void main (String arg[])
    {
    System.out.println(“please enter any sentence “);
    Scanner sc=new Scanner(System.in);
    String s=sc.nextLine();
    String s1[]=s.split(” “);
    for (int i=s1.length-1;i>=0;i–)
    {
    System.out.print(s1[i]+” “);
    }
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: