Split string into individual words Java

后端 未结 12 1288
既然无缘
既然无缘 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:38

    As a more general solution (but ASCII only!), to include any other separators between words (like commas and semicolons), I suggest:

    String s = "I want to walk my dog, cat, and tarantula; maybe even my tortoise.";
    String[] words = s.split("\\W+");
    

    The regex means that the delimiters will be anything that is not a word [\W], in groups of at least one [+]. Because [+] is greedy, it will take for instance ';' and ' ' together as one delimiter.

提交回复
热议问题