我试图从仅包含字符串的文件输入中获取单词并将每个单词分别存储到单个数组中(不允许ArrayList
)。
下面的代码接收文件输入,但是将其作为一个块接收。例如,如果文件输入是" ONE TWO THREE"我希望每个单词在数组中都有自己的索引(array[0] = "ONE"
,array[1]="TWO"
和array[2]="THREE"
),但我的代码只是将句子放在array[0] = "ONE TWO THREE"
中。我该如何解决这个问题?
int i = 0;
String wd = "";
while (in.hasNextLine() ) {
wd = in.nextLine() ;
array[i] = wd;
i++;
System.out.println("wd");
}
答案 0 :(得分:0)
f文件输入是“ONE TWO THREE”我希望每个单词都有自己的单词 数组中的空格如此数组[0] = ONE,数组1 = TWO和数组[2] = THREE
使用带有空格的String#split(delim)作为分隔符。
String fileInput = "ONE TWO THREE";
String[] array = filrInput.split("\\s");
答案 1 :(得分:0)
而不是行
array[i] = wd; // since wd is the whole line, this puts lines in the array
您希望拆分您读入的行并将拆分项放入数组中。
String[] items = wd.split("\\s+"); // splits on any whitespace
for (String item : items) { // iterate through the items and shove them in the array
array[i] = item;
i++;
}
答案 2 :(得分:0)
那是因为你从文件中读取了LINES。你可以这样做:
String array[]=in.nextLine().split(" ");
答案 3 :(得分:0)
我会将分隔符设置为空格“”然后使用.next()。
in.useDelimiter(" ");
while(in.hasNext()){
wd = in.next();
//wd will be one word
}