Extract the first few words from a sentences within a maximum number of characters - Java java.lang

Java examples for java.lang:String Algorithm

Introduction

The following code shows how to Extract the first few words from a sentences within a maximum number of characters.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String text = "this is a test test test test test java2s.com";
        int maxCharacters = 42;
        System.out.println(extractFirstWords(text, maxCharacters));
    }/*www. ja  v a 2 s.c  om*/

    /**
     * <p>Extract the first few words from a sentences within a maximum number of 
     * characters.</p>
     * @param text Original sentence or text
     * @param maxCharacters maximum number of characters...
     * @return
     */
    public static String extractFirstWords(final String text,
            int maxCharacters) {
        String firstFewWords = null;

        if (text.length() > maxCharacters) {
            int lastBlankSpaceIndex = text.substring(0, maxCharacters)
                    .lastIndexOf(' ');
            StringBuilder buf = new StringBuilder(
                    (lastBlankSpaceIndex != -1) ? text.trim().substring(0,
                            lastBlankSpaceIndex) : text.substring(0,
                            maxCharacters));
            buf.append(" ...");

            firstFewWords = buf.toString();
        } else {
            firstFewWords = text;
        }

        return firstFewWords;
    }
}

Related Tutorials