步骤如下:
① 取花括号里的字符串, 利用substring和indexOf;
② 字符串转字符串数组, 利用split
③ 直接用put传入实例化的map
④ 用entrySet取出键值对
PS: 太菜了, 还是做一下笔记, 大佬请绕道
import java.util.Map;
import java.util.HashMap;
public class HelloWorld{
public static void main(String []args){
String str = "anyType{UserId=7; VolId=37; UserName=Volunteer 1; }";
Map map = cutSemiString(str);
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key:" + entry.getKey() + ", Value:" + entry.getValue());
}
}
/**
* fetch {...} and cut str by ;
* @param str Input string
* @return Map
*/
static public Map cutSemiString(String str){
String array[] = str.substring(str.indexOf("{") + 1, str.indexOf("}")).split("; *");
Map map = new HashMap<>();
for (String i : array) {
map.put(i.split("=")[0],i.split("=")[1]);
}
return map;
}
}
Output:
Key:VolId, Value:37
Key:UserName, Value:Volunteer 1
Key:UserId, Value:7