Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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. 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading