-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 ":".

PermGenError
  • 45,977
  • 8
  • 87
  • 106
Beginner
  • 855
  • 9
  • 21
  • 37

2 Answers2

3

Nice and easy, just use:

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

Gives you a String array which you can compare to the invalid string array, either by iterating or by checking number of items to check if valid or not.... or do whatever you like with it.

So to compare both strings do something like:

boolean valid = false;
String[] stringValidTokens = line.split(":");
String[] stringinValidTokens = invalidline.split(":");
if(stringValidTokens.size() == stringInvalidTokens.size()){
valid = true;
}
Malcolm Murray
  • 323
  • 2
  • 10
0

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

This code is splitting the given string on count of 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");
    }

}
Community
  • 1
  • 1
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39