📜  java字符串提取单词 - Java(1)

📅  最后修改于: 2023-12-03 14:43:00.661000             🧑  作者: Mango

Java字符串提取单词

在Java中,要从字符串中提取单词,最简单的方法是使用split()函数。split()函数将根据提供的分隔符将字符串分割为单词数组。

String sentence = "This is an example sentence";
String[] words = sentence.split(" ");
for (String word : words) {
  System.out.println(word);
}

输出:

This
is
an
example
sentence

以上代码首先将字符串“This is an example sentence”存储在一个名为sentence的字符串变量中。然后,我们使用空格字符“ ”作为分隔符来将该句子拆分成单词数组。最后,我们使用for循环遍历单词数组并打印每个单词。

如果您想使用不同的分隔符,只需将其传递给split()函数即可。

String sentence = "This,is;another!example?sentence";
String[] words = sentence.split("[,;!?\\s]+");
for (String word : words) {
  System.out.println(word);
}

输出:

This
is
another
example
sentence

在上面的例子中,我们使用“[,;!?\ s] +”正则表达式作为分隔符,这意味着我们将使用空格,逗号,分号,感叹号和问号来分割句子。

另一种提取单词的方法是使用Scanner对象。Scanner对象可以从字符串中提取单词,并且允许您指定分隔符。

String sentence = "This is an example sentence";
Scanner scanner = new Scanner(sentence);
scanner.useDelimiter(" ");
while (scanner.hasNext()) {
  String word = scanner.next();
  System.out.println(word);
}
scanner.close();

输出:

This
is
an
example
sentence

以上代码创建了一个Scanner对象,并使用“ ”作为分隔符。然后,我们使用while循环扫描字符串并打印每个单词。最后,我们应该在使用完Scanner对象后关闭它。

在提取单词时,请记住在处理字符串时始终考虑特殊字符和边界情况。