Skip to content

Reverse the sentence

  • by

Reverse the sentence is top of the technical interview question in the IT companies. This question generally for 1-3 years experiences java or android developers.  Here is the question understating.

String input = “Eyehunt website java”;

String output = “java website Eyehunt”;

There is several way to solve this problem :

Method 1. Using split method and convert string into array then arrange reverse order of string using for loop

public class ReverseSentance {

	public static void main(String arg[]){
		String input = "Eyehunt website java";
		String strArray[]=input.split(" ");
		String output="";
		for (int i = strArray.length; i > 0 ; i--) {
			output =output+ " " +strArray[i-1];
		}
		System.out.println("Reverse Sentance : " + output);
	}
}

Sometimes interviewer asks for a reverse sentence without using the split method. In that condition, we can use ArrayList() data structure. If you don’t know Arraylist then follow this ArrayList tutotrial…

Method 2. Another example of reversing sentence using ArrayList.

import java.util.ArrayList;
import java.util.Iterator;

public class ReverseSentance {
	public static void main(String arg[]){
		String input = "Eyehunt website java";
		String word="";
		ArrayList<String> outputlist=new ArrayList<String>();
		String output="";
		for (int i = 0; i < input.length(); i++) {
			word=word+input.charAt(i);
			if (String.valueOf(input.charAt(i)).equals(" ")) {
				outputlist.add(word.trim());
				word="";
			}
			if (i==input.length()-1) {
				outputlist.add(word);
			}
		}
		Iterator<String> iterator=outputlist.iterator();
		while (iterator.hasNext()) {
			output=iterator.next().toString()+" "+output;		
		}
		System.out.println("Reverse Sentance : " + output);
	}
}

Reverse the sentence is programming question to test problem solving skill. You can solve this question in any language.

Leave a Reply

Your email address will not be published. Required fields are marked *