This methods returns the next "block" of non-whitespace characters, starting after the index, but passing the first whitespace block. - Java java.lang

Java examples for java.lang:String Index

Description

This methods returns the next "block" of non-whitespace characters, starting after the index, but passing the first whitespace block.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String wholeDocument = "this         is a test";
        int index = 2;
        System.out.println(nextString(wholeDocument, index));
    }/*w  ww  .  j  a  va 2 s  . co  m*/

    /**
     * This methods returns the next "block" of non-whitespace characters, starting after the index, 
     * but passing the first whitespace block.
     * 
     * Example:
     * <p>
     * <code>That is        some text</code>
     * </p>
     * If the index is 0 -> "That"
     * If the index is 2 -> "at"
     * If the index is 4 -> "is"
     * If the index is 5 -> "is"
     * If the index is 8 (or 9, or 10...) -> "some"
     * 
     * @param wholeDocument
     * @param index
     * @return the next block of text
     */
    public static String nextString(String wholeDocument, int index) {
        StringBuilder sb = new StringBuilder();
        char currentChar = wholeDocument.charAt(index);
        while (index < wholeDocument.length()
                && Character.isWhitespace(currentChar)) {
            index++;
            currentChar = wholeDocument.charAt(index);
        }
        sb.append(currentChar);
        while ((!Character.isWhitespace(currentChar))
                && index < wholeDocument.length() - 1) {
            index++;
            currentChar = wholeDocument.charAt(index);
            sb.append(currentChar);
        }

        return sb.toString();
    }
}

Related Tutorials