Split string into individual words Java

后端 未结 12 1308
既然无缘
既然无缘 2020-12-02 13:19

I would like to know how to split up a large string into a series of smaller strings or words. For example:

I want to walk my dog.

12条回答
  •  长情又很酷
    2020-12-02 13:48

    A regex can also be used to split words.

    \w can be used to match word characters ([A-Za-z0-9_]), so that punctuation is removed from the results:

    String s = "I want to walk my dog, and why not?";
    Pattern pattern = Pattern.compile("\\w+");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
    

    Outputs:

    I
    want
    to
    walk
    my
    dog
    and
    why
    not
    

    See Java API documentation for Pattern

提交回复
热议问题