Tokenize the given String into a String array via a StringTokenizer. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Tokenize the given String into a String array via a StringTokenizer.

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        String delimiters = ".";
        System.out.println(java.util.Arrays.toString(tokenizeToStringArray(
                str, delimiters)));//  w  ww .  j a  v  a2s . co m
    }
    public static String[] tokenizeToStringArray(String str,
            String delimiters) {
        return tokenizeToStringArray(str, delimiters, true, true);
    }
    public static String[] tokenizeToStringArray(String str,
            String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) {

        if (str == null) {
            return null;
        }
        StringTokenizer st = new StringTokenizer(str, delimiters);
        List<String> tokens = new ArrayList<String>();
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (trimTokens) {
                token = token.trim();
            }
            if (!ignoreEmptyTokens || token.length() > 0) {
                tokens.add(token);
            }
        }
        return toStringArray(tokens);
    }
    public static String[] toStringArray(Collection<String> collection) {
        if (collection == null) {
            return null;
        }
        return collection.toArray(new String[collection.size()]);
    }
}

Related Tutorials