我正在尝试将字符串的组成部分拆分为数组,以便更轻松地访问它们。
例如:4+5=
应变为 ['4','+','5','=']
。
编辑:- 我需要将连续的数字连接在一起,并且可以忽略空格。再次感谢!
最佳答案
您可以使用正则表达式 lookaround 来解决它机制。
String str = "10 * 10 - 40 + 100/2 = 110";
//but first lets remove white spaces (it will makes regex easier)
String strWithoutSpaces=str.replaceAll("\\s+", "");
String[] tokens = strWithoutSpaces.split("(?<=[-+*/=])|(?=[-+*/=])");
for (String t:tokens)
System.out.print(t+",");
输出:
10,*,10,-,40,+,100,/,2,=,110,
关于java - 将字符串拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14033729/