Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Scanner;
- public class cs491f14_01_reverse_words {
- public static void main(String args[]) {
- Scanner sc = new Scanner(System.in);
- while (sc.hasNextLine()) {
- String phrase = sc.nextLine();
- reversewords(phrase);
- }
- }
- public static void reversewords(String phrase) {
- ArrayList<String> list = new ArrayList<String>();
- // Remove the .
- String lastchar = String.valueOf(phrase.charAt(phrase.length()-1));
- phrase = phrase.replace(lastchar , "");
- // Split into Words
- String split[] = phrase.split(" ");
- // 1) Push Words Onto List.
- for (String word : split ) {
- list.add(word);
- }
- // Reverse words in list.
- Collections.reverse(list);
- // Go through the list and adjust commas if necessary..
- for (int i = 0; i < list.size() ; i++ ) {
- if ( list.get(i).contains(",") ) {
- // Add ',' to previous word
- list.set( i-1 , list.get(i-1 ) + ",");
- // remove ',' from current word
- list.set( i , list.get(i).replace("," , ""));
- }
- }
- // You Really want to use String builder? Ok..
- StringBuilder sB = new StringBuilder("");
- for( String v : list ) {
- sB.append(v + " ");
- }
- // Replace the last space the last space with a period.
- sB.replace(sB.length()-1, sB.length()-1, lastchar);
- System.out.println(sB.toString().trim());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement