根据android中的一些特殊字符将字符串拆分为两个

时间:2015-07-02 06:04:33

标签: java android string

我有一个这样的字符串:

[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"}]&@[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"},{\"ID\":0,\"Text\":\"Approved\"},{\"ID\":1,\"Text\":\"Freezed\"},{\"ID\":2,\"Text\":\"Cancelled\"},{\"ID\":3,\"Text\":\"Completed\"},{\"ID\":4,\"Text\":\"Foreclosed\"},{\"ID\":5,\"Text\":\"UnApproved\"}]

我想根据& @字符组合将我的字符串分成两部分:

 String [] separated=line.split("&@");

但是当我检查分离的值[0]包含完美的前半部分字符串但是当我检查分隔[1]时它包含完整的字符串而没有"& @"字符。我想分开[1]包含"& @"之后的字符。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

理解split函数,它将输入分隔并拆分字符串。

String [] java.lang.String.split(String regex)

围绕给定正则表达式的匹配拆分此字符串。

此方法的工作方式就像调用带有给定表达式和limit参数为零的双参数split方法一样。因此,结尾的空字符串不包含在结果数组中。

字符串" boo:和:foo",例如,使用这些表达式产生以下结果:

正则表达式结果 :{" boo",""," foo" } o {" b","",":和:f" }

如果你想要分隔符("& @")出现。这个

public static void main(String[] args) {
    String input="[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"}]&@[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"},{\"ID\":0,\"Text\":\"Approved\"},{\"ID\":1,\"Text\":\"Freezed\"},{\"ID\":2,\"Text\":\"Cancelled\"},{\"ID\":3,\"Text\":\"Completed\"},{\"ID\":4,\"Text\":\"Foreclosed\"},{\"ID\":5,\"Text\":\"UnApproved\"}]";
    String[] resultArray = input.split("&@");
    for(int i=0;i<resultArray.length;i++){
        if(i!=0)
            resultArray[i]="&@"+resultArray[i];
    }

    for(String str:resultArray)
        System.out.println(str);
}

答案 1 :(得分:0)

你需要像String mySpitedStr[] = myStr.split("&|@");

这样的正则表达式

答案 2 :(得分:0)

[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"}]

//&@

[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"},{\"ID\":0,\"Text\":\"Approved\"},{\"ID\":1,\"Text\":\"Freezed\"},{\"ID\":2,\"Text\":\"Cancelled\"},{\"ID\":3,\"Text\":\"Completed\"},{\"ID\":4,\"Text\":\"Foreclosed\"},{\"ID\":5,\"Text\":\"UnApproved\"}]

这是你的原始字符串,其中包含换行符和@,以便清楚它分割的位置。如您所见,第二个字符串以重复的第一个字符串开头(没有结束])。 你的分裂工作正常。

相关问题