How to truncate a string after n number of words?

package org.kodejava.example.lang;

public class GetNumberOfWordsFromString {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog.";

        String one = truncateAfterWords(1, text);
        System.out.println("1 = " + one);

        String two = truncateAfterWords(2, text);
        System.out.println("2 = " + two);

        String four = truncateAfterWords(4, text);
        System.out.println("4 = " + four);
    }

    /**
     * Truncate a string after n number of words.
     *
     * @param numberOfWords number of words to truncate after.
     * @param longString the long string.
     * @return truncated long string.
     */
    public static String truncateAfterWords(int numberOfWords, String longString)     {
        return longString.replaceAll("^((?:\W*\w+){" +
                numberOfWords + "}).*$", "$1");
    }
}

The result of the snippet:

1 = The
2 = The quick
4 = The quick brown fox

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.

1 Comments

Leave a Reply