我需要将我的字符串分成3个arg,每个arg都是引号内的内容,并将它们存储在单独的变量中。
这就是我所拥有的。下面的代码接受所有命令行参数,并将它们组合为一个大的String
。
我需要转换的字符串示例:
“METRO Blue Line” “Target Field Station Platform 1” “south”
它应该变成:
var1 = METRO Blue Line
var2 = Target Field Station Platform 1
var3 = south
我已经对
split("\"")
进行了很多尝试,但是无论出于什么原因,它甚至都没有为我删除引号。// Construct a string to hold the whole args.
// Implemented it this way because args is separated by spaces
String combine = "";
for(int i = 0; i < args.length; i++)
{
combine = combine.concat(args[i]);
combine = combine.concat(" ");
}
System.out.println(combine);
最佳答案
符号”
和“
与符号"
不同。如果使用split("\"")
拆分,则显然会搜索"
,但不会搜索其他引用符号”
和“
。
您可以使用Matcher
及其find
方法轻松提取它们。或者,也可以将分割方法与正确的定界符:split("” “")
一起使用。请注意,第一个和最后一个元素将带有单引号,只需将其删除即可。
String input = "“METRO Blue Line” “Target Field Station Platform 1” “south”";
String[] elements = input.split("” “");
// Remove first quote
elements[0] = elements[0].substring(1);
// Remove last quote
String lastElement = elements[elements.length - 1];
elements[elements.length - 1] = lastElement.substring(0, lastElement.length() - 1);
// Output all results
for (String element : elements) {
System.out.println(element);
}
输出为:
METRO Blue Line
Target Field Station Platform 1
south
这种方法的一个优点是它非常高效,不需要额外的替换或类似的东西,只需对输入进行一次迭代,仅此而已。