Converting a sentence string to a string array of words in Java

后端 未结 16 2459
余生分开走
余生分开走 2020-12-01 00:04

I need my Java program to take a string like:

\"This is a sample sentence.\"

and turn it into a string array like:

{\"this\         


        
16条回答
  •  旧时难觅i
    2020-12-01 00:33

    Now, this can be accomplished just with split as it takes regex:

    String s = "This is a sample sentence with []s.";
    String[] words = s.split("\\W+");
    

    this will give words as: {"this","is","a","sample","sentence", "s"}

    The \\W+ will match all non-alphabetic characters occurring one or more times. So there is no need to replace. You can check other patterns also.

提交回复
热议问题