【发布时间】:2014-05-12 10:16:42
【问题描述】:
例如,输入将是:
AddItem rt456 4 12 BOOK “File Structures” “Addison-Wesley” “Michael Folk”
我想使用扫描仪读取所有内容并将其放入数组中。
喜欢:
info[0] = rt456
info[1] = 4
..
..
info[4] = File Structures
info[5] = Addison-Wesley
那么我怎样才能得到引号之间的字符串呢?
编辑:我的代码的一部分->
public static void main(String[] args) {
String command;
String[] line = new String[6];
Scanner read = new Scanner(System.in);
Library library = new Library();
command = read.next();
if(command.matches("AddItem"))
{
line[0] = read.next(); // Serial Number
line[1] = read.next(); // Shelf Number
line[2] = read.next(); // Shelf Index
command = read.next(); // Type of the item. "Book" - "CD" - "Magazine"
if(command.matches("BOOK"))
{
line[3] = read.next(); // Name
line[4] = read.next(); // Publisher
line[5] = read.next(); // Author
Book yeni = new Book(line[0],Integer.parseInt(line[1]),Integer.parseInt(line[2]),line[3],line[4],line[5]);
}
}
}
所以我使用 read.next 来读取不带引号的字符串。
通过使用正则表达式解决
read.next("([^\"]\\S*|\".+?\")\\s*");
【问题讨论】:
-
读完书后,将分隔符改为
"。或者使用使用空格作为分隔符的 CSV 解析器。 -
new StreamTokenizer(new StringReader(mystring))应该可以解决问题。 -
字段的个数,字段的位置每次都一样吗?
-
你为什么不逃避他们? "->\"
-
” 或 "?双引号是您输入的内容吗?