在Java中将句子字符串转换为单词的字符串数组

我需要Java程序采用类似以下的字符串:

"This is a sample sentence."

并将其转换为字符串数组,例如:

{"this","is","a","sample","sentence"}

没有句号或标点符号(最好)。顺便说一句,字符串输入始终是一个句子。

有没有一种我看不到的简便方法?还是我们真的必须大量搜索空格并从空格之间的区域(即单词)创建新的字符串?

回答:

String.split()将完成您想要的大部分操作。然后,您可能需要遍历单词以提取任何标点符号。

例如:

String s = "This is a sample sentence.";

String[] words = s.split("\\s+");

for (int i = 0; i < words.length; i++) {

// You may want to check for a non-word character before blindly

// performing a replacement

// It may also be necessary to adjust the character class

words[i] = words[i].replaceAll("[^\\w]", "");

}

以上是 在Java中将句子字符串转换为单词的字符串数组 的全部内容, 来源链接: utcz.com/qa/428106.html

回到顶部