How to parse the string into map

后端 未结 5 1140
失恋的感觉
失恋的感觉 2021-02-15 02:24

have a string like A=B&C=D&E=F, how to parse it into map?

5条回答
  •  南笙
    南笙 (楼主)
    2021-02-15 03:05

    I would use split

    String text = "A=B&C=D&E=F";
    Map map = new LinkedHashMap();
    for(String keyValue : text.split(" *& *")) {
       String[] pairs = keyValue.split(" *= *", 2);
       map.put(pairs[0], pairs.length == 1 ? "" : pairs[1]);
    }
    

    EDIT allows for padded spaces and a value with an = or no value. e.g.

    A = minus- & C=equals= & E==F
    

提交回复
热议问题