Learn-dsa..in 30 days!



























CC-3 : Reverse words of a String.

Description:

Given an input String which consists of words, reverse the order of the words, such that the first word becomes the last word, second word becomes second last word and so on.

Test cases and expected outputs:

Input Parameters Expected outputs
str="Java is the best" best the is Java
str="Data structures and algorithms using Java "; Java using algorithms and structures Data

Pseudocode:

The java method should accept following input parameters: str (String).
Extract the characters from str into char array names chars.
Set value of str to a blank string. We will use reinitialized str to assemble the reversed string.
Declare a String variable word, we will use this to store an individual word we find in the chars array.
Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
If chars[idx] is not equal to a space, we will add chars[idx] to word, this way we will start assembling a word from the characters.
If chars[idx] is equal to space, it means we have found a new word:
Do str= word + “ “ + str, this will start reversing the words as we find the same.
Reset word to “”, so that we can start assembling the next word.
After above loops complete return the reversed str.

Alternatively, The above algorithm can also be completed using Java String APIs, Collections APIs:

Split the input str using split() method of String class into a String array arr.
Create a ArrayList wordsAl using words present in arr.
Use Collections.reverse() to reverse order of words in wordsAl.
Create a String str from wordAl using String.join() method.
Return reversed string str.

Code:

public String stringReverseWords(String str) {
	String word=""; 
	char[] chars=str.toCharArray();
	str="";
	for (int idx=0; idx < chars.length; idx++) {
		if (chars[idx] != ' ') {
			word=word+chars[idx];
			
		} else {
			if (word.length() !=0) {
			str=word+" "+str;
			word="";
			}
		}	
	}	
	if (word.length() !=0) {
		str=word+" "+str;
	}
	return str;
}

public String stringReverseWordsUsingAPIs(String str) {
	String[] words= str.trim().split("\\s+");
	ArrayList wordsAl=new ArrayList(Arrays.asList(words));
	Collections.reverse(wordsAl);
	str=String.join(" ",wordsAl);	
	return str;
}

Click here to download and run code and test cases !