java字符串转为Map类型:split()方法的应用
方法一:
package com.thinkgem.jeesite.modules.socketTest.demo2; import java.util.HashMap; import java.util.Map; /** * @Author: zhouhe * @Date: 2019/4/11 11:21 */ public class Test { public static void main(String[] args) { String arr = "##0261ST=31;CN=2011;PW=123456;MN=88888880000001"; System.out.println(arr); Map map = new HashMap(); if (null != arr) { String[] param = arr.split(";"); for (int i = 0; i < param.length; i++) { int index = param[i].indexOf('='); map.put(param[i].substring(0,index), param[i].substring((index + 1))); } } System.out.println(map); } }
方法二:
package com.thinkgem.jeesite.modules.socketTest.demo2; import java.util.HashMap; import java.util.Map; /** * @Author: zhouhe * @Date: 2019/4/11 11:21 */ public class Test { public static void main(String[] args) { String arr = "##0261ST=31;CN=2011;PW=123456;MN=88888880000001"; Map result = new HashMap(); String[] params = arr.split("\\;"); for (String entry : params) { if (entry.contains("=")) { String[] sub = entry.split("\\="); if (sub.length > 1) { result.put(sub[0], sub[1]); } else { result.put(sub[0], ""); } } } System.out.println(result); System.out.println(result.get("PW")); } }