Solved

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

Posted on 2016-07-27
7
151 Views
Last Modified: 2016-07-27
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

0
Comment
Question by:SunnyX
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 31

Assisted Solution

by:awking00
awking00 earned 100 total points
Comment Utility
Because I got my hands slapped for providing full code to your previous question, I'm taking a little different approach to this one.
Define a new string as the first word as the substring of the string up to the space. Define a new string as the last word as the substring starting with the last space (plus one more character). Define a new string as the middle replacing the first word and the last word. The output string should then simply be last word + middle + first word. Take a try at doing that.
2
 
LVL 9

Accepted Solution

by:
Moussa Mokhtari earned 400 total points
Comment Utility
@Sunny
here you go
package TaskCh;
//import java.util.Scanner;
import java.util.Arrays;
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) { 
	        String lastword = words[words.length-1];
	        String firstword = words[0];
	        words[0] = lastword;
	        words[words.length-1] = firstword;

	        s = Arrays.toString(words).replaceAll("[\\[\\]\\,]", "");
	    }

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

}

Open in new window

1
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Homework done?
1
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 31

Expert Comment

by:awking00
Comment Utility
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;
1
 

Author Closing Comment

by:SunnyX
Comment Utility
Everybody thx for your help ! :)
0
 

Author Comment

by:SunnyX
Comment Utility
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
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
s = s.replaceAll("^(\\w*)(.*?)(\\w*)$", "$3$2$1");

Open in new window

1

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now