简体   繁体   中英

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. Now I just have to put all the words of the String into an array as the elements. However, I'm not sure how to proceed.

You can use StringTokenizer in java to devide your string into words:

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

And your output st whould be an array of words.

Take a look at this Java StringTokenizer tutorial for further information.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM