Given a string of words, reverse all the words. e.g

Given String:  “hello dear how are you”

Output: “you are how dear hello” 

Lets look into the code written in groovy for achieving the above expected output.

def str = "hello dear how are you" // given string
Deque<Integer> deque = new ArrayDeque<Integer>(); // arraydeque for inserting at beginning
def space = [' '] // space for comparing the space within a string  
def len = str.length() // length of string
def i = 0 // initialized i = 0
while(i < len){
    if(!space.contains(str[i])){ // conditional check for space
    def startIndex = i // startIndex of the word
        while(i<len && (!space.contains(str[i]))){ // condition for next space
           i+=1
        }
    deque.addFirst(str.substring(startIndex,i)) // insert the word at the beginning of deque
    }
i++
}
deque.join(" ") // convert deque to string

 

In the above code we loop through the string until it’s max length and use Java String class method named as substring which accepts start and end index for a given string. We use special data structure ‘ArrayDeque’ from java collection framework to insert the words at the beginning.

At last we use join method to convert the existing data structure to string.