Separate words using split

0

I wanted to print only words that have : up front

Example: Coisa1:kit1:Coisa2:kit2;grupo;grupo2;grupo3 would only appear: Coisa1 kit1 Coisa2 kit2

public static void main(String[] args) {
    String s = "Coisa1:kit1:Coisa2:kit2;grupo;grupo2;grupo3";
    String[] splitado1 = s.split(":");
    for (int i = 2; i < splitado1.length; i++) {
        System.out.println(splitado1[i]);
    }
}
    
asked by anonymous 13.03.2017 / 02:05

1 answer

1

In this simple example you just gave a split before the ";" and get the first element, like this:

public static void main(String[] args) {
    String str = "Coisa1:kit1:Coisa2:kit2;grupo;grupo2;grupo3";
    String[] splitado1 = str.split(";")[0].split(":");
    for (String s: splitado1) {
        System.out.println(s);
    }
}

Output:

Coisa1
kit1
Coisa2
kit2

However, I suggest giving more input examples so that we can understand what exactly you need to parse, even to include validations in case of errors.

    
13.03.2017 / 02:16