Solved

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

Posted on 2016-07-27
7
256 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
json example 39 135
Python Assistance 7 73
Java Timer (static) 9 36
why cannot we forward request once the response is committed 2 33
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…
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
The viewer will learn how to implement Singleton Design Pattern in Java.

863 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

19 Experts available now in Live!

Get 1:1 Help Now