Solved

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

Posted on 2016-07-27
7
583 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.

717 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