将字符串拆分为单个单词并忽略其他所有单词

时间:2017-12-29 18:24:51

标签: java arrays string split

我想将一个字符串拆分成单个单词。如果字符串是:

String s = "Practice makes perfect. you'll only get Perfect by practice. just practice!";

我想存储为:

String[] str = {"Practice", "makes", "perfect", "youll", "only", "get", "Perfect", "by", "practice", "just", "practice"};

如果我使用s.split("\\W") you'll变成you ll。如何制作youll

2 个答案:

答案 0 :(得分:4)

首先删除':

可以轻松完成
String[] str = s.replace("'", "").split("\\W+");

还要在分割中添加+,以避免数组中出现空插槽。

输出:

[Practice, makes, perfect, youll, only, get, Perfect, by, practice, just, practice]

答案 1 :(得分:1)

string.replaceAll("[\\W&&\\S]", "").split("\\s+");