1

Hello I am currently working on a program that reverses sentences using stacks. However, I need to implement a function that detects periods and then repeats the loop over again. For example, I could write "Hello my name is blank. nice to meet you." and it would print "you. meet to nice blank. is name my Hello" when I actually just need it to reverse each sentence individually, if that makes sense. So "blank is name my Hello. you meet to nice." is my desired output. Any advice would help greatly, thank you!

import java.util.Stack;
import java.util.Scanner;

public class NolascoStackReverse {

 public static void main (String[] args) {
  
      Scanner in = new Scanner(System.in);
      Stack<String> reverse = new Stack<String>();
      
      System.out.println("Enter a sentence to be reversed: ");
      String str = in.nextLine();

      String[] wordsArray = str.split(" ");
      
      for (String word : wordsArray) {
          reverse.push(word);
      }
      System.out.println("Here is the reversed order: ");
      
      while (reverse.empty() == false) {
            System.out.print(reverse.pop() + " ");
      }

   }
}
Adrian
  • 13
  • 3
  • I would recommend that you split the string on periods, then iterate through the String[] to reverse the elements and concatenate each result to a StringBuilder. – bliss Mar 25 '21 at 03:06

2 Answers2

0

Below code splits your string with space char. You need to split it with period first and split each sentence with space.

    String[] wordsArray = str.split(" ");

If you dont care for period, then you can use multiple delimiters for split function :Use String.split() with multiple delimiters

If you need period in reversed sentence, you can use below code:

    String[] sentenceArray = str.split(("\\."));
    for (String sentence : sentenceArray){
        String[] wordsArray = sentence.split((" "));
        for (String word : wordsArray) {
            reverse.push(word);
        }
        reverse.push(".");
    }
nitashathakur
  • 430
  • 3
  • 9
0

There is already an API available in Java for processing text. You can use BreakIterator like this:

public class Test {
    public static void main(String[] args) throws Exception {
         Stack<String> reverse = new Stack<String>();
         String result="";
         Locale enUS = new Locale("en","US");
         
         String str = "My name is R.R.Martin. Nice to meet you.";
         System.out.println("Text: " + str);
         System.out.print("Here is the reversed order: ");
         
         List<String> sentences = getPieces(str, BreakIterator.getSentenceInstance(enUS));
         for(String s : sentences) {
             s = s.substring(0,s.length()-1);
             
             List<String> words = getPieces(s, BreakIterator.getWordInstance(enUS));
             reverse.clear();
             for (String w : words) {
                 reverse.push(w.strip());
             }
             while (reverse.empty() == false) {
                   result += reverse.pop() + " ";
             }
             result = result.strip();
             result += result.length()>0? ". ":""; 
         }
         System.out.println(result);
    }
    
    public static List<String> getPieces(String text, BreakIterator bi) {
        int boundary,start;
        String piece = "";
        List<String> list = new ArrayList<>();

        bi.setText(text);
        boundary = bi.first();
        start = 0;
        while (boundary != BreakIterator.DONE) {
            if(boundary>0)
                piece = text.substring(start,boundary);
            start = boundary;
            boundary = bi.next();
            if(!piece.strip().isBlank())
                list.add(piece.strip());
        }
        return list;
    }

}

Output:

Text: My name is R.R.Martin. Nice to meet you.
Here is the reversed order: R.R.Martin is name My. you meet to Nice. 


Advantage of this approach is that it is locale sensitive i.e. you can use the code with other languages.

the Hutt
  • 16,980
  • 2
  • 14
  • 44