Reverse words in a string

Given a string, reverse the string word by word.
Example:
String: "This is a string"
Output: "string a is This"


Video coming soon!



Subscribe for more updates


Preparing for interviews? IDeserve team is here to help.




Algorithm/Insights

Step 1. Reverse each word.
Step 2. Reverse the whole string.
Example:
Input String:    This is a string
After Step 1:    sihT si a gnirts
After Step 2:    string a is This


Hone your coding skills!




AngryNerds Practice platform »

Algorithm Visualization




Code Snippet

			
package com.ideserve.questions.saurabh;

/**
 * <b>IDeserve <br>
 * <a href="https://www.youtube.com/c/IDeserve">https://www.youtube.com/c/IDeserve</a>
 * <br><br>
 * Given a string, reverse the string word by word.
 * Example:
 * String: "This is a string"
 * Output: "string a is This"
 *
 * @author Saurabh
 */
public class ReverseWords {
	
	public static void main(String[] args) {
		char[] str = "This is a string".toCharArray();
		getReverse(str);
		System.out.println(str);
	}

	public static void getReverse(char[] str) {
		int n = str.length;
		int start = 0;
		for(int i = 0; i < n; i++) {
			if(str[i] ==  ' ' && i > 0) {
				reverse(str, start, i-1);
				start = i+1;
			} else if(i == n-1) {
				reverse(str, start, i);
			}
		}
		reverse(str, 0, n-1);
	}

	private static void reverse(char[] str, int start, int end) {
		while(start < end) {
			swap(str, start, end);
			start++;
			end--;
		}
	}

	private static void swap(char[] str, int start, int end) {
		char tmp = str[start];
		str[start] = str[end];
		str[end] = tmp;
	}

}
		

Contribution

  • Sincere thanks from IDeserve community to Saurabh Kumar for compiling current post.

    Saurabh Kumar

    Ninja Programmer