【发布时间】:2015-01-02 16:14:58
【问题描述】:
如何创建一个将字符串作为参数的方法,并返回其元素是字符串中的单词的数组。
这是我迄今为止想出的:
// 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
}
如您所见,我可以通过扫描仪输入每个单词。现在我只需要将字符串的所有单词作为元素放入一个数组中。但是,我不确定如何继续。
【问题讨论】:
-
使用准备好的
split方法:str.split("\\s+");。