Java中字符串分隔程序中的一个错误

时间:2016-03-21 22:08:48

标签: java string

以下程序的目标是通过分隔符"/" " "":"分隔源字符串。预期输出为20 03 2016 17 30,但仅产生20 03 2016 17,省略了最后一个元素。也许是一些一对一的错误?

public static void main(String[] args) {
    String source = "20/03/2016:17:30";
    String sep = "/:";
    String[] result = new String[5];
    String str = "";
    int index = 0;

    for (int sourcePos = 0; sourcePos < source.length(); sourcePos++) {
        int compt = 0;

        for (int sepPos = 0; sepPos < sep.length(); sepPos++) {
            if (source.charAt(sourcePos) == sep.charAt(sepPos)) compt++;
        }

        if (compt > 0) {
            result[index] = str;
            System.out.print(" " + result[index]);

            if (index < result.length)
                index++;
            else
                break;

            str = "";
        } else {
            str = str + source.charAt(sourcePos);
        }
    }
}

2 个答案:

答案 0 :(得分:4)

您可以简单地使用regex

String[] result = source.split("/|:");  

至于您的代码,您离开的原因是主for循环在您最后一次到达if (compt > 0)之前终止。换句话说,sourcePos < source.length()false,然后才能添加最后一个str

你可以这样:

for (int sourcePos = 0; sourcePos < source.length() ; sourcePos++) {
    boolean compt = false;

    for (int sepPos = 0; sepPos < sep.length(); sepPos++) {
        if (source.charAt(sourcePos) == sep.charAt(sepPos)) { 
            compt = true;
            break;
        }
    }

    if (compt) {
        result[index] = str;
        index++;
        str = "";
    } 

    else if(sourcePos == source.length()-1) {
        result[index] = str + source.charAt(sourcePos);
    }

    else {
        str = str + source.charAt(sourcePos);
    }
}

答案 1 :(得分:0)

因为你要求没有正则表达式的解决方案(引用“......但我的意思是没有正则表达式”)

public static void main(String[] args) {
    String source = "20/03/2016:17:30";
    String result = "";
    String before = "";
    for (int sourcePos=0; sourcePos < source.length(); sourcePos ++ ) {
        if (java.lang.Character.isDigit(source.charAt(sourcePos))) {
            result += before + source.charAt(sourcePos);
            before = "";
        } else {
            before = " ";  // space will be added only once on next digit
        }
    }
    System.out.println(result);
}

除了数字之外的任何内容都被视为分隔符,即使它不止一个字符。