将字串放入字符串数组
问题描述:
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();
}
在线return words[i] = word;
我收到错误消息“无法将字符串转换为字符串[]”。帮帮我?将字串放入字符串数组
答
line.split()
已经给你一个数组,你只需要返回:
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);
}
}
运行提供了:
paxdiablo
has
left
the
building
请记住这对一个每个字之间的间距 。如果你想使用“空白的任何量”的分离更通用的解决方案,你可以使用它代替:
public static String[] wordList(String line){
return line.split("\\s+");
}
,您可以用String.split()
使用正则表达式可以发现here。
答
String[] words = line.split(" ");
是你所需要的。 split()方法已经返回一个字符串数组。
答
假设你正在试图用空格分割,你的方法应该是这样的:
public static String[] wordList(String line){
return line.split(" ");
}
@ Dando18错误。 '“”'也是一个有效的正则表达式。而btw'\ s'不只是空白。 – m0skit0 2015-02-23 03:20:58
@ m0skit0只是查了一下,你是对的。所有这些年来,我认为你必须使用'\ s'。谢谢 – Dando18 2015-02-23 03:23:40
@ m0skit0,我很困惑,'\ s'究竟是不是只有空格?它被_defined_定义为'\ s - 一个空格字符:[ \ t \ n \ x0B \ f \ r]'按照http://docs.oracle.com/javase/7/docs/api/java/util/regex /Pattern.html#sum。如果你的意思是“不只是空间”,我可以理解。 –
paxdiablo
2015-02-23 03:29:05