Reverse String Wordwise

 

Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is.

Sample Input 2:
god is one
Sample Output 2:
one is god
Approach 1 -
import java.util.Scanner;

public class ReverseWordwise {

	public static void main(String[] args) {
	
		Scanner s = new Scanner(System.in);
		String st = s.nextLine();
		String str = reverseWordWise(st);
		System.out.println(str);
	}
	
	public static String reverseWordWise(String input) {
	
		String s="";
		input=" " + input;
		String str[]=input.split(" ");
		for(int i=str.length-1;i>0;i--)
		{
			s=s+ str[i]+ " ";
		}
		return s;
	}

}
Approach 2 -
public class Solution {
	public static String reverseWordWise(String input) {
String x="";
		int sp=input.length();
		for(int i=input.length()-1;i>=0;i--) 
        {
			
			if(i==0) 
            {
				x=x+input.substring(0,sp);
			}
			
			else if(input.charAt(i)==' ') 
            {
				x=x+input.substring(i+1,sp)+" ";
				sp=i;
			}
		}
		return x;
		
	}
}
    

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern