【问题标题】:java string split into array, how to save into the same array the char im splitting with?java字符串拆分成数组,如何将char im拆分保存到同一个数组中?
【发布时间】:2013-09-11 21:42:35
【问题描述】:

例如:strEquation="36+5-8X2/2.5"

我的代码是:

String[] tmp = strEquation.split("[X\\+\\-\\/]+");

for(int i=0; i<tmp.length; i++)
    Log.d("Split array",tmp[i]);

以及我认为的输出:

36
5
8
2
2.5

我希望tmp 字符串数组也能放入我要拆分的字符,如下所示:

tmp[0] = 36
tmp[1] = +
tmp[2] = 5
tmp[3] = -
tmp[4] = 8
tmp[5] = X
tmp[6] = 2
tmp[7] = /
tmp[8] = 2.5

知道怎么做吗?

【问题讨论】:

标签: java android arrays string


【解决方案1】:

X+-/字符之前或之后拆分如何?顺便说一句,您不必在字符类中转义 +/ ([...])

String[] tmp = strEquation.split("(?=[X+\\-/])|(?<=[X+\\-/])");

似乎可以解决问题。

【讨论】:

    【解决方案2】:

    我会说你正在尝试获取所有匹配项而不是拆分字符串

    Matcher m = Pattern.compile("[X+/-]|[^X+/-]+").matcher(strEquation);
    while (m.find()) {
      System.out.println(m.group());
    }
    

    但上面的答案更聪明:)

    另外:您不需要在方括号内转义 +/ 字符;减号 (-) 仅当它不是列表中的第一个或最后一个字符时才需要转义

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多