Break apart a string using a tokenizer into a List of String s. - Java java.lang

Java examples for java.lang:String Tokenize

Description

Break apart a string using a tokenizer into a List of String s.

Demo Code

//package com.java2s;
import java.util.*;

public class Main {
    public static void main(String[] argv) {
        String inputString = "java2s.com";
        String seperator = "java2s.com";
        System.out.println(tokenizeString(inputString, seperator));
    }/*from  ww w  .jav  a 2s  .c  om*/

    /**
     * Break apart a string using a tokenizer into a {@code List} of {@code String}s.
     *
     * @param inputString a string containing zero or or more segments
     * @param seperator   seperator to use for the split, or null for the default
     * @return a {@code List} of {@code String}s.  An empty list is returned if <i>inputString</i> is null.
     */
    public static List<String> tokenizeString(final String inputString,
            final String seperator) {
        if (inputString == null || inputString.length() < 1) {
            return Collections.emptyList();
        }

        final List<String> values = new ArrayList<String>();
        values.addAll(Arrays.asList(inputString.split(seperator)));
        return Collections.unmodifiableList(values);
    }

    public static Map<String, String> tokenizeString(
            final String inputString, final String seperator,
            final String subSeperator) {
        if (inputString == null || inputString.length() < 1) {
            return new HashMap<String, String>();
        }

        final Map<String, String> returnProps = new LinkedHashMap<String, String>();

        final List<String> values = tokenizeString(inputString, seperator);
        for (final String loopValue : values) {
            if (loopValue != null && loopValue.length() > 0) {
                final int subSeperatorPosition = loopValue
                        .indexOf(subSeperator);
                if (subSeperatorPosition != -1) {
                    final String key = loopValue.substring(0,
                            subSeperatorPosition);
                    final String value = loopValue
                            .substring(subSeperatorPosition + 1);
                    returnProps.put(key, value);
                } else {
                    returnProps.put(loopValue, "");
                }
            }
        }
        return returnProps;
    }
}

Related Tutorials