我在使用 Java Scanner.useDelimiter() 分隔“”时遇到问题。
我正在尝试使用扫描仪读取 CSV 文件。CSV 有 2 列(名称、描述),描述字段有很长的段落(带有 , 和 .)
我想知道这种情况的分隔符是什么。
最佳答案
怎么样
Scanner s = new Scanner("name1 lorem, some description\n" +
"name2 ipsum, some other, description \n" +
"name3 dolor, a third. description\n");
while (s.hasNextLine()) {
String[] cols = s.nextLine().split(",", 2); // limit to two columns.
System.out.println("col1: " + cols[0] + ", col2:" + cols[1]);
}
打印:
col1: name1 lorem, col2: some description
col1: name2 ipsum, col2: some other, description
col1: name3 dolor, col2: a third. description
或者,如果你一直坚持使用 Scanner,你可以做类似的事情
Scanner s = new Scanner("name1 lorem, some description\n" +
"name2 ipsum, some other, description \n" +
"name3 dolor, a third. description\n");
s.useDelimiter(",");
while (s.hasNext())
System.out.println("col1: " + s.next() + ", col2:" + s.skip(",").nextLine());
(产生相同的输出。)
关于 ""的 Java Scanner.useDelimiter() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3828377/