Separate words using split

Asked

Viewed 481 times

0

I wanted to print out only words that have : in front

Example: Coisa1:kit1:Coisa2:kit2;grupo;grupo2;grupo3 would appear only: 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]);
    }
}

1 answer

1


In this simple example you gave, just split before the ";" and take 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);
    }
}

Exit:

Coisa1
kit1
Coisa2
kit2

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

  • It worked rafael, as I do now to catch only the "groups" ?

  • Again using the given example, the simplest is to swap with: String[] splitt1 = str.substring(str.indexof(";")+1). split(";"); However, as said, if you have other examples you are able to break. You have to.

  • Thanks Ray, it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.