Reputation: 17
public static String[] wordList(String line){
Scanner scanner = new Scanner(line);
String[] words = line.split(" ");
for( int i=0; i<words.length; i++)
{
String word = scanner.next();
return words[i] = word;
}
scanner.close();
}
On the line return words[i] = word;
I get the error message saying "cannot convert String to String[]". Help?
Upvotes: 0
Views: 7917
Reputation: 622
Assuming you're trying to split by spaces, you're method should look like:
public static String[] wordList(String line){
return line.split(" ");
}
Upvotes: 0
Reputation: 882068
line.split()
already gives you an array, you just need to return that:
public class Test {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String xyzzy = "paxdiablo has left the building";
String[] arr = wordList(xyzzy);
for (String s: arr)
System.out.println(s);
}
}
Running that gives:
paxdiablo
has
left
the
building
Keep in mind that's for one space between each word. If you want a more general solution that uses a separator of "any amount of whitespace", you can use this instead:
public static String[] wordList(String line){
return line.split("\\s+");
}
The regular expressions that you can use with String.split()
can be found here.
Upvotes: 2
Reputation: 305
String[] words = line.split(" ");
Is all you need. The split() method already returns an array of Strings.
Upvotes: 1