在JAVA中按特定字词拆分字符串 [英] Split String In JAVA by specific words
本文介绍了在JAVA中按特定字词拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字符串S ="3乘3加3 3 1"
String S= "multiply 3 add add 3 3 1"
我想得到两个字符串数组一个是{"multiply","add","add"}另一个是{"3","3","3",1}
I want to get two string arrays The one is {"multiply", "add", "add"} Another out is {"3","3","3",1}
我如何得到它?我尝试使用
How can I get it? I tried to use
String operators[] = s.split("[0-9]+");
String operands[] =s.split("(?:add|multiply)");
但是,它不起作用.
推荐答案
您可以使用Java 8 groupingBy
.
You can use java 8 groupingBy
.
Map<Boolean, List<String>> map = Arrays
.stream(s.split(" "))
.collect(Collectors.groupingBy(e -> e.matches("\\d+")));
System.out.println(map);
结果是:
{false=[multiply, add, add], true=[3, 3, 3, 1]}
您可以通过以下方式获取运算符和操作数:
You can get operators and operands by:
List<String> operators = map.get(false);
List<String> operands = map.get(true);
这篇关于在JAVA中按特定字词拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文