-4
String line = "a:b:c:d"   // Valid 

In the above line , I have 4 values separated by 3 ":".

Sting invalidLine = "a:b:c" //Invalid 

As 4th value is missing

String invalidLine = "a:b:c:"  //Invalid 

As 4th value is missing .

I want to spit it the line on count ofdelimiter ":".

4

2 回答 2

3

简单易用,只需使用:

String[] stringValidTokens = line.split(":");

为您提供一个字符串数组,您可以通过迭代或通过检查项目数来检查是否有效......或对它做任何您喜欢的事情,您可以将其与无效的字符串数组进行比较。

因此,要比较两个字符串,请执行以下操作:

boolean valid = false;
String[] stringValidTokens = line.split(":");
String[] stringinValidTokens = invalidline.split(":");
if(stringValidTokens.size() == stringInvalidTokens.size()){
valid = true;
}
于 2013-02-21T12:25:20.463 回答
0

我想将它吐在计数分隔符“:”上。

此代码根据 ofdelimiter ":" 的计数拆分给定的字符串

public static void main(String[] args) {
    String line = "a:b:c:d";
    int count = line.length() - line.replace(":", "").length();
    System.out.println(count);
    String[] str = null;
    if (count == 3) {
        str = line.split(":");
        System.out.println(Arrays.toString(str));
        if (Arrays.asList(str).contains("") || str.length < 4)
            System.out.println("Invalid");
    } else {
        
        System.out.println("Invalid");
    }

}
于 2013-02-21T12:29:52.357 回答