如何分割“以空格分割的字符串中间还有空格”的数据结构

2年前 (2023) 程序员胖胖胖虎阿
236 0 0

 如何分割“以空格分割的字符串中间还有空格”的数据结构,话不多说,直接上代码。

/**
 * 5 1 "zhang san feng" 0.000 "hello world" "哪吒" 
 *  --> 
 *  [5, 1, "zhang san feng", 0.000, "hello world", "哪吒"]
 */
private static void test01() {
    String str = "5 1 \"zhang san feng\" 0.000 \"hello world\" \"哪吒\"";
    final Pattern p = Pattern.compile("\"(.*?)\"");
    Matcher m = p.matcher(str);
    List<String> list = new ArrayList<String>();
    Map<String, String> map = new HashMap<String, String>();
    while (m.find()) {
        list.add(m.group());
    }
    System.out.println(list);//["zhang san feng", "hello world", "哪吒"]

    for (String s : list) {
        str = str.replace(s, s.replace(" ", ""));
        map.put(s.replace(" ", ""), s);
    }

    System.out.println(str);//5 1 "zhangsanfeng" 0.000 "helloworld" "哪吒"

    List<String> valueList = Arrays.asList(str.split(" "));
    System.out.println(valueList);//[5, 1, "zhangsanfeng", 0.000, "helloworld", "哪吒"]
    List<String> collect = valueList.stream().map(x -> {
        if(map.containsKey(x)) {
            return map.get(x);
        }
        return x;
    }).collect(Collectors.toList());
    System.out.println(collect);//[5, 1, "zhang san feng", 0.000, "hello world", "哪吒"]
}

public static void main(String[] args) {
    test01();
}

相关文章

暂无评论

暂无评论...