Creates a list of strings from a string within tokens. - Android java.util

Android examples for java.util:List

Description

Creates a list of strings from a string within tokens.

Demo Code


//package com.book2s;
import java.util.ArrayList;

import java.util.List;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        String delimiter = "book2s.com";
        System.out.println(stringTokenToList(string, delimiter));
    }//from   w w  w . ja  v  a  2 s .  c om

    /**
     * Creates a list of strings from a string within tokens. Empty tokens will
     * be omitted: If a string within tokens is <code>"a,,b,,c"</code> and the
     * delimiter string is <code>","</code>, the returned list of strings
     * contains the tree elements <code>"a", "b", "c"</code>.
     *
     * @param string    String within tokens
     * @param delimiter Delimiter that separates the tokens. Every character
     *                  of the delimiter string is a separate delimiter. If
     *                  the string within tokens is <code>"I,like:ice"</code>
     *                  and the delimiter string is <code>",:"</code>, the
     *                  returned list of strings contains the three elements
     *                  <code>"I", "like", "ice"</code>.
     * @return          List of strings
     */
    public static List<String> stringTokenToList(String string,
            String delimiter) {
        if (string == null) {
            throw new NullPointerException("string == null");
        }

        if (delimiter == null) {
            throw new NullPointerException("delimiter == null");
        }

        StringTokenizer tokenizer = new StringTokenizer(string, delimiter);
        List<String> list = new ArrayList<>(tokenizer.countTokens());

        while (tokenizer.hasMoreTokens()) {
            list.add(tokenizer.nextToken());
        }

        return list;
    }
}

Related Tutorials