2

我有一个字符串,我想单独拆分这些值。

例如,我想拆分以下字符串:

            Test1 Avg. running Time: 66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster

我想要 66,3[ms] 和 Ref 值。

如果你们中的任何人都可以建议我,这将是最好的方法,那将是有帮助的。

我应该使用分隔符(:) 吗?但在这种情况下,我收到的输出为

            66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster 

还是我应该使用“正则表达式”?

4

4 回答 4

1

对于这种情况,您可以使用.split(", ");,因为“,”在数字之外有一个空格。

还可以在这篇文章中查看现成的解析器。

于 2012-07-31T12:21:41.600 回答
0

用这种方式

public class JavaStringSplitExample {

    public static void main(String args[]) {

        String str = "one-two-three";
        String[] temp;

        String delimiter = "-";

        temp = str.split(delimiter);

        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]);

        /*
         * NOTE : Some special characters need to be escaped while providing
         * them as delimiters like "." and "|".
         */

        System.out.println("");
        str = "one.two.three";
        delimiter = "\\.";
        temp = str.split(delimiter);
        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]);

        /*
         * Using second argument in the String.split() method, we can control
         * the maximum number of substrings generated by splitting a string.
         */

        System.out.println("");
        temp = str.split(delimiter, 2);
        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]);

    }

}
于 2012-07-31T12:50:11.840 回答
0

你可以使用split()函数...

String s = "66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster";

String[] arr = s.split(", ");

于 2012-07-31T12:35:46.743 回答
0

你可以试试这个正则表达式:

    String test = "Test1 Avg. running Time: 66,3 [ms], (Ref: 424.0) ===> Well done, It is 80% faster"; 
    Pattern p = Pattern.compile("(\\d+[.,]?\\d+)");
    Matcher m = p.matcher(test);
    m.find();
    String avgRunningTime = m.group(1);
    m.find();
    String ref = m.group(1);
    System.out.println("avgRunningTime: "+avgRunningTime+", ref: "+ref);

这将打印:

    avgRunningTime: 66,3, ref: 424.0

您自然会想要添加一些错误检查(例如检查是否m.find()返回true)。

于 2012-07-31T13:50:35.310 回答