[英]How to read strings and numbers separated by space in Java?
I've been working on a project in Java and I need to read a text file that looks like this 我一直在用Java开发一个项目,我需要阅读一个看起来像这样的文本文件
1 1 'Who is Albert Einstein?' 1 1“谁是爱因斯坦?” 'commander' 'physicist' 'doctor' 1 I need to take the values separately , for example id=1,type=1,question=Who is Albert Einstein,answer1=commander etc.
'指挥官''物理学家''医生'1我需要分别取值,例如id = 1,type = 1,question =谁是Albert Einstein,answer1 =指挥官等。
Is there some way I can separate them by space and keep the strings between apostrophes as a whole? 我是否可以通过某种方式将它们按空格分开并将字符串整体放在撇号之间?
This is hard to do as a standard string split will not understand not to split anything inside the quotes. 这很难做到,因为标准的字符串拆分将不理解不对引号内的任何内容进行拆分。
You could write your own manual split easily enough, loop through, flip an "inQuote" flag every time you find a quote. 您可以轻松地编写自己的手动拆分,遍历,每次找到报价时翻转“ inQuote”标志。 Split on spaces whenever you find a space and the flag is not set.
只要找到空格并且未设置标志,就在空格上分割。
This should work: 这应该工作:
try {
BufferedReader reader = new BufferedReader(new FileReader("the-file-name.txt"));
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
String line = reader.readLine();
while(line != null) {
ArrayList<String> values = new ArrayList<String>();
String curr = "";
boolean quote = false;
for(int pos = 0; pos < line.length(); pos++) {
char c = line.charAt(pos);
if(c == '\'') {
quote = !quote;
}
else if(c == ' ' && !quote) {
values.add(curr);
curr = "";
}
else {
curr += c;
}
}
lines.add(values);
line = reader.readLine();
}
reader.close();
// Access the first value of the first line as an int
System.out.println("The first value * 2 is " + (Integer.parseInt(lines.get(0).get(0)) * 2));
// Access the third value of the first line as a string
System.out.println("The third value is " + lines.get(0).get(2));
} catch (IOException e) {
System.out.println("Error reading file: ");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Error parsing file: ");
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.