【问题标题】:How do I return an array of words given an input sentence (string)?给定输入句子(字符串),如何返回单词数组?
【发布时间】: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+");

标签: java methods


【解决方案1】:

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

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

你的输出 st 应该是一个 array 的单词。

查看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
    }

【讨论】:

  • 注意javadoc 实际上建议在这个遗留类上使用split :)
  • 谢谢@Reimeus:我会记住的。并且 Split() 似乎也更快,指的是this
【解决方案2】:

正如 Maroun Maroun 所说,您应该使用来自 Strings 的 split(regex) 方法,但如果您想自己执行此操作:

首先,声明数组:

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.

然后,您可以在while 循环内填充数组:

while (t.hasNext()) {
    w = t.next();
    words[countWords] = w;
    countWords++;
}

最后返回:

return words;

注意:

句子

words[countWords] = w;
countWords++;

可以简化为

words[countWords++] = w;

【讨论】:

    【解决方案3】:

    正如@Maroun Maroun 所说:使用拆分功能或像@chsdk 所说使用StringTokenizer。 如果你想使用扫描仪:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 2021-06-22
      • 2014-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多