【发布时间】:2016-02-01 00:14:28
【问题描述】:
给定用户输入的字符串,我试图通过删除任何空格并获取每个标记来拆分字符串。
但是当我在引号中有一个标记时我遇到了困难。这里有一些例子可以更好地说明:
用户输入:that is cool
预期输出:
that
is
cool
用户输入:The book "Harry Potter" is cool
预期输出:
The
book
"Harry Potter"
is
cool
用户输入:Here " is one final " example
预期输出:
Here
" is one final "
example
这是我目前所拥有的:
public static void main(String[] args) {
String input;
Scanner in = new Scanner(System.in);
System.out.print("User input: ");
input = in.nextLine();
input = input.trim();
input = input.replaceAll("\\s+", " ");
String[] a = input.split(" ");
for (String c: a) {
System.out.println(c);
}
}
它仅适用于第一个示例,但对于带有引号的示例,它会将引号内的空格分开膨胀。示例 3 输出:
Here
"
is
one
final
"
example
【问题讨论】:
-
报价标志,你应该对照报价检查每个字符,如果你遇到这种情况,你应该设置这个标志并继续寻找接近的报价。