Java program to swap corner words and reverse middle characters

Write a Java program that takes an input string, swaps the first and last words, and reverses the middle word.

Examples: 

 

Input : Hello World GFG Welcomes You
Output :You semocleW GFG dlroW Hello

Approach:  

  • First we take two empty strings and the first string takes the first word and the second string the last word
  • When we repeat each word, we have to keep the variables pointing to the next word except the last one.
  • Now we convert the left string to the given string.
  • After the above process, we will first print the last word and the back of the left string and then the first word.

 

// Java Program to illustrate the solution of above problem
public class ExchangeFirstLastReverseMiddle {
	static void print(String s)
	{
		// Taking an Empty String
		String fst = "";
		int i = 0;
		for (i = 0; i < s.length();) {

			// Iterating from starting index
			// When we get space, loop terminates
			while (s.charAt(i) != ' ') {
				fst = fst + s.charAt(i);
				i++;
			}

			// After getting one Word
			break;
		}

		// Taking an Empty String
		String last = "";
		int j = 0;
		for (j = s.length() - 1; j >= i;) {

			// Iterating from last index
			// When we get space, loop terminates
			while (s.charAt(j) != ' ') {
				last = s.charAt(j) + last;
				j--;
			}

			// After getting one Word
			break;
		}

		// Printing last word
		System.out.print(last);
		for (int m = j; m >= i; m--) {

			// Reversing the left characters
			System.out.print(s.charAt(m));
		}

		// Printing the first word
		System.out.println(fst);
	}

	public static void main(String[] args)
	{
		String s = "Hello World GFG Welcomes You";
		print(s);
	}
}

Output: 

You semocleW GFG dlroW Hello

 

Submit Your Programming Assignment Details