[英]How do I return an array of words given an input sentence (string)?
How do I create a method that takes a string as an argument, and returns the array whose elements are the words in the string. 如何创建一个将字符串作为参数的方法,并返回其元素为字符串中单词的数组。
This is what I have came up with so far: 到目前为止,这是我想出的:
// 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
}
As you can see, I can just input each word via Scanner. 如您所见,我可以通过Scanner输入每个单词。 Now I just have to put all the words of the String into an array as the elements.
现在,我只需要将String的所有单词作为元素放入数组即可。 However, I'm not sure how to proceed.
但是,我不确定如何进行。
You can use StringTokenizer in java to devide your string into words: 您可以在Java中使用StringTokenizer将字符串分解为单词:
StringTokenizer st = new StringTokenizer(str, " ");
And your output st
whould be an array
of words. 和你的输出
st
对子级是一个array
的话。
Take a look at this Java StringTokenizer tutorial for further information. 查看此Java StringTokenizer教程以获取更多信息。
Your code whould look like: 您的代码如下所示:
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
}
As Maroun Maroun commented, you should use the split(regex)
method from String
s, but if you want to do this by yourself: 正如Maroun Maroun所评论的那样,您应该使用
String
的split(regex)
方法,但是如果您想自己这样做:
First, declare the array: 首先,声明数组:
String[] words = new String[50]; // Since you are using an array you have to declare
// a fixed length.
// To avoid this, you can use an ArrayList
// (dynamic array) instead.
Then, you can fill the array inside the while
loop: 然后,您可以在
while
循环内填充数组:
while (t.hasNext()) {
w = t.next();
words[countWords] = w;
countWords++;
}
And finally return it: 最后返回它:
return words;
Note: 注意:
The sentences 句子
words[countWords] = w;
countWords++;
can be simplified in 可以简化为
words[countWords++] = w;
As @Maroun Maroun said: use the split function or like @chsdk said use StringTokenizer. 就像@Maroun Maroun所说的那样:使用split函数或像@chsdk所说的那样使用StringTokenizer。 If you want to use scanner:
如果要使用扫描仪:
public static String[] split(String s)
{
Scanner sc = new Scanner(s);
ArrayList<String> l = new ArrayList<String>();
while(sc.hasNext())
{
l.add(sc.next());
}
String[] returnValue = new String[l.size()];
for(int i = 0; i < returnValue.length; ++i)
{
returnValue[i] = l.get(i);
}
return returnValue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.