Convert String to Map, "A=B&C=D" -> [A=B, C=D] - Android java.util

Android examples for java.util:Map

Description

Convert String to Map, "A=B&C=D" -> [A=B, C=D]

Demo Code

import java.io.UnsupportedEncodingException;
import java.util.*;

public class Main{

    /**/*from   www. j  av  a  2  s. com*/
     * Convert String to Map, "A=B&C=D" -> [A=B, C=D]
     *
     * @param srcStr    string to convert
     * @param separator separator for split <code>srcStr</code>
     * @return <code>Map</code>
     */
    public static Map<String, String> convertString2Map(String srcStr,
            String separator) {
        StringTokenizer st1 = new StringTokenizer(srcStr, separator);
        Map<String, String> result = new HashMap<String, String>();
        while (st1.hasMoreTokens()) {
            String field = st1.nextToken();
            StringTokenizer st2 = new StringTokenizer(field, "=");
            String key;
            String value = null;
            if (st2.countTokens() == 2) {
                key = st2.nextToken();
                value = st2.nextToken();
            } else {
                key = st2.nextToken();
            }
            result.put(key, value);
        }
        return result;
    }

}

Related Tutorials