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); }}
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;
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
CEHJ
s = s.replaceAll("^(\\w*)(.*?)(\\w*)$", "$3$2$1");