package shop.alien.util.typeconversion;

import java.util.HashMap;
import java.util.Map;

/**
 * String转Map
 *
 * @author ssk
 * @version 1.0
 * @date 2023/12/22 15:07
 */
public class String2Map {
    public static void main(String[] args) {
        String str = "a=1,b=2";
        String str2 = "device_platform=webapp&aid=6383&channel=channel_pc_web&sec_user_id=MS4wLjABAAAAfr2fXCq0DKab6xqm3ua10q3CcsdijXFrk2EA2TWiCMo&max_cursor=0&locate_query=false&show_live_replay_strategy=1&need_time_list=1&time_list_query=0&whale_cut_token=&cut_version=1&count=18&publish_video_strategy_type=2&pc_client_type=1&version_code=170400&version_name=17.4.0&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=zh-CN&browser_platform=Win32&browser_name=Chrome&browser_version=120.0.0.0&browser_online=true&engine_name=Blink&engine_version=120.0.0.0&os_name=Windows&os_version=10&cpu_core_num=16&device_memory=8&platform=PC&downlink=10&effective_type=4g&round_trip_time=0&webid=7308409090664891923&msToken=NlE6LWPBEqztN5L-edK25s-BVuhgqb0rFpWpHNmJmtruV92FP7PbiUsBrZoxkOsmZ8ZczCz2GPsyVpQLSJw-lI50e71pKPhAxEnSoXP62QaCm7mqmDCSdg==&X-Bogus=DFSzswVEnczANcPptNZqkGSX1b5P";
        System.out.println(stringToMap(str2, "&"));
    }

    /**
     * 将Map字符串转换为Map
     *
     * @param str      Map字符串
     * @param splitStr 用什么分割对象
     * @return Map
     */
    public static Map<String, String> stringToMap(String str, String splitStr) {
        String[] strs = str.split(splitStr);
        Map<String, String> map = new HashMap<>();
        for (String string : strs) {
            String key = "";
            String value = "";
            String[] split = string.split("=");
            if (split.length > 0) {
                key = string.split("=")[0];
            }
            if (split.length == 2) {
                value = string.split("=")[1];
            }
            // 去掉头部空格
            String key1 = key.trim();
            String value1 = value.trim();
            map.put(key1, value1);
        }
        return map;
    }
}
