我在java中通过缓冲区读取器读取一行。 线是: abc 3.8229 1.0326 1 1 1.1386 1.006
如何将此行的每个单词存储在字符串数组中?
答案 0 :(得分:6)
假设你有
String var = "abc 3.8229 1.0326 1 1 1.1386 1.006";
您可以使用String.split()生成一个String数组。
String[] arr = var.split(" ");
这将产生一个包含arr
的每个单词的数组var
。
答案 1 :(得分:3)
BufferReader br;
...
String line = br.readLine();
String[] words = line.split(" ");
答案 2 :(得分:1)
我建议使用扫描仪。
Scanner sc = new Scanner(line);
while( sc.hasNext() ){
String word = sc.next(); // Get word
}
另外,您还可以使用
方便的方法double x = sc.nextDouble();
int i = sc.nextInt();
答案 3 :(得分:0)
您可以在从缓冲区读取时拆分单词:
try {
String line = "abc 3.8229 1.0326 1 1 1.1386 1.006";
List newWordSymbols = Arrays.asList(' ','\n','\r');
StringReader sr = new StringReader(line);
List wordList = new ArrayList();
StringBuilder word = new StringBuilder();
int ch;
while (( ch=sr.read())!=-1) {
char c = (char)ch;
if(newWordSymbols.contains(c)){
wordList.add(word.toString());
word= new StringBuilder();
}else{
word.append(c);
}
}
wordList.add(word.toString());
System.out.println("Word list ::: "+wordList);
} catch (IOException ex) {
ex.printStackTrace();
}
答案 4 :(得分:0)
import java.io.*;
class Record
{
String name;
String s1;
String s2;
String s3;
String s4;
String s5;
String s6;
public Record(String name, String s1, String s2, String s3, String s4, String s5, String s6){
this.name = name;
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
this.s4 = s4;
this.s5 = s5;
this.s6 = s6;
}
public static void main(String args[]){
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = str.split(" ");
Record record = new Record(tokens[0],tokens[1],tokens[2],tokens[3],tokens[4],tokens[5],tokens[6]);//process record , etc
}
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}