Link to home
Start Free TrialLog in
Avatar of SunnyX
SunnyX

asked on

Core Java. Swaping first and last words in sentence. Bug

I would like to make a piece of code that swap first and last words in sentence. I come up with some solution as you can see below. However, the program doesn't work well. Please help me to find mistake. You code will be much appreciated !
NOW:
input : "London is the capital of UK"
Output : "UK is the capital of UK London "

Should be :
input : "London is the capital of UK"
Output : "UK is the capital of London "

Looking forwards for help from you dear Experts !

package TaskCh;
//import java.util.Scanner;

public class TaskCh {


	public static void main(String[] args) {
	   //  System.out.println("Enter line of text.");
	   // Scanner kb = new Scanner(System.in);
	    String s = "London is the capital of UK" ;  // kb.nextLine(); // Read the whole line instead of word by word
	    System.out.println("Original line is  : ");
	    System.out.println(s);
	    String[] words = s.split("\\s+"); // Split on any whitespace

	    if (words.length > 1) { 
	                     
	    	// Swap first and last words  	
	        s = words[words.length-1] + " " +  s.substring(s.indexOf(words[1], words[0].length() -2 )) + " " + words[0].toLowerCase();

	        s = s.substring(0, 1).toUpperCase() + s.substring(1); // 

	    }

	    System.out.println("\n\n\nModified line is :");
	    System.out.println(s);
	}

}

Open in new window

SOLUTION
Avatar of awking00
awking00
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Homework done?
While I would have preferred you attempted to write the code using my directions, since full code is being supplied, this is how I would have gone about it (very simple) -
String str = "London is the capital of UK";
String first = str.substring(0,indexOf(" "));
String last = str.substring(lastIndexOf(" ") + 1);
String middle = str.replace(first,"").replace(last,"");
String output =  last + middle + first;
Avatar of SunnyX
SunnyX

ASKER

Everybody thx for your help ! :)
Avatar of SunnyX

ASKER

awking00, I'm sorry. I just saw your last post :( I'm actually submitting the close of question, webpage updated that your valuable comment come up :( once again sorry
s = s.replaceAll("^(\\w*)(.*?)(\\w*)$", "$3$2$1");

Open in new window