gpt4 book ai didi

java - 如何返回给定输入句子(字符串)的单词数组?

转载 作者:行者123 更新时间:2023-12-01 17:00:46 24 4
gpt4 key购买 nike

如何创建一个方法,该方法采用字符串作为参数,并返回其元素是字符串中的单词的数组。

这是我到目前为止想到的:

// split takes some string as the argument, and returns the array
// whose elements are the words in the string
public static String[] split (String s)
{
// determine the number of words
java.util.Scanner t = new java.util.Scanner (s);
int countWords = 0;
String w;
while (t.hasNext ())
{
w = t.next ();
countWords++;
}
// create appropriate array and store the string’s words in it
// code here
}

正如你所看到的,我可以通过扫描仪输入每个单词。现在我只需要把字符串的所有单词作为元素放入一个数组中。但是,我不确定如何继续。

最佳答案

您可以使用StringTokenizer 在 java 中将字符串分成单词:

StringTokenizer st = new StringTokenizer(str, " ");

你的输出st应该是一个单词数组

看看这个 Java StringTokenizer tutorial欲了解更多信息。

您的代码应如下所示:

    StringTokenizer st = new StringTokenizer(s, " ");
int n=st.countTokens();
for(int i=0;i<n;i++) {
words[i]=st.nextToken();// words is your array of words
}

关于java - 如何返回给定输入句子(字符串)的单词数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27745052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com