我很抱歉我的英语,但无论如何: 我有一个庞大的,如“[arg1,”start,of,text,in,quotes“,arg2]”来自命令“somecommand arg1”引号“”的文本开头。我被空格字符串分割了,但这是不正确的。我想把引号中的所有内容作为数组中的一个位置:
它不仅需要使用一个双引号。 这是我的代码:
public static String[] fixArguments(String[] arr) {
String[] rarr = new String[arr.length];
System.out.println("===========================");
System.out.println("fixArguments|arr:"+Arrays.toString(arr));
System.out.println("fixArguments|rarr:"+Arrays.toString(rarr));
/*for(int i=0; i<arr.length; i++) {
if(i < start) rarr[i] = arr[i];
else if(i > end) rarr[i] = arr[i-(end-start)];
else {
rarr[i] = StringUtils.join(Arrays.copyOfRange(arr, start, end), " ");
}
}*/
int start = -1;
int end = -1;
int lastnull = -1;
for(int i=0; i<arr.length; i++) {
if(rarr[i] == null && lastnull == -1) lastnull = i;
System.out.println("fixArguments|for:"+i+"|start:"+start);
System.out.println("fixArguments|for:"+i+"|end:"+end);
System.out.println("fixArguments|for:"+i+"|arr[i]:"+arr[i]);
if((arr[i].equalsIgnoreCase("\"") || arr[i].startsWith("\"")) && start == -1) start = i;
else if((arr[i].equalsIgnoreCase("\"") || arr[i].endsWith("\"")) && start != -1) {
rarr[start] = StringUtils.join(Arrays.copyOfRange(arr, start, i+start), " ");
System.out.println(Arrays.asList(arr));
System.out.println(i);
System.out.println(Arrays.asList(Arrays.copyOfRange(arr, start, i+start)));
System.out.println(arr[i]);
rarr[start] = rarr[start].substring(1, rarr[start].length()-1);
System.out.println("fixArguments|for:"+i+"|rar[start]"+rarr[start]);
start = -1;
end = i;
} else {
rarr[start+1] = arr[end+1];
System.out.println(rarr[start+1]);
lastnull = -1;
}
}
System.out.println("=================================");
return rarr;
}
答案 0 :(得分:0)
现在操作List
比数组更容易,所以我插入了一个转换机制。您可能希望专门使用List
表单。
public static List<String> fixArguments(List<String> args) {
List<String> fixed = new ArrayList<>();
StringBuilder building = new StringBuilder();
boolean build = false;
for (String arg : args) {
// A " at the start switches to building.
if (arg.charAt(0) == '\"') {
build = true;
building.setLength(0);
}
if (build) {
if (building.length() > 0) {
building.append(" ");
}
building.append(arg);
} else {
fixed.add(arg);
}
// A " at the end stops the building.
if (arg.charAt(arg.length() - 1) == '\"') {
fixed.add(building.toString());
build = false;
}
}
return fixed;
}
public static String[] fixArguments(String[] arguments) {
// Roll the array into a List
List<String> args = Arrays.asList(arguments);
List<String> fixed = fixArguments(args);
String[] results = new String[fixed.size()];
// Roll out the results back into an array.
for (int i = 0; i < results.length; i++) {
results[i] = fixed.get(i);
}
return results;
}
public void test() {
String[] arguments = new String[]{"One", "\"Two,", "Three,", "Four\"", "Five"};
String[] fixed = fixArguments(arguments);
System.out.println("Before: " + Arrays.asList(arguments));
System.out.println("After : " + Arrays.asList(fixed));
}