Search code examples
javastringsplitsubstring

Skip last 2 words in a sentence in java


In my java program,

How to skip last two words in sentence?

My input string is: Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.

Expected output is: Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.

Anyone Help?


Solution

  • Try this.

    static String reverseExceptLast2Words(String input) {
        StringBuilder output = new StringBuilder();
        for (String senence : input.split("\\.\\s*")) {
            List<String> words = Arrays.asList(senence.split("\\s+"));
            Collections.reverse(words.subList(0, Math.max(0, words.size() - 2)));
            output.append(String.join(" ", words)).append(". ");
        }
        return output.toString();
    }
    
    public static void main(String[] args) {
        String input = "Hi there. My name is Kalp. This is my lucky day. I like coding so much. This is it.";
        String output = reverseExceptLast2Words(input);
        System.out.println(output);
    }
    

    output:

    Hi there. name My is Kalp. my is This lucky day. coding like I so much. This is it.