Solved

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

Posted on 2016-07-27
7
406 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 32

Assisted Solution

by:awking00
awking00 earned 100 total points
ID: 41731367
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
ID: 41731419
@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
ID: 41731459
Homework done?
1
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 32

Expert Comment

by:awking00
ID: 41731473
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
ID: 41731480
Everybody thx for your help ! :)
0
 

Author Comment

by:SunnyX
ID: 41731485
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
ID: 41731541
s = s.replaceAll("^(\\w*)(.*?)(\\w*)$", "$3$2$1");

Open in new window

1

Featured Post

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ejb mdb examples 1 10
Glassfish admin console not working 1 36
Fast way to search item into Java Array (Rhino compatible) 2 31
Coding for the first time 9 36
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…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
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 basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

821 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