HJ74 参数解析
描述
在命令行输入如下命令:
xcopy /s c:\\ d:\\e,
各个参数如下:
参数1:命令字xcopy
参数2:字符串/s
参数3:字符串c:\\
参数4: 字符串d:\\e
请编写一个参数解析程序,实现将命令行各个参数解析出来。
解析规则:
1.参数分隔符为空格
2.对于用""包含起来的参数,如果中间有空格,不能解析为多个参数。比如在命令行输入xcopy /s “C:\program files” "d:“时,参数仍然是4个,第3个参数应该是字符串C:\program files,而不是C:\program,注意输出参数时,需要将”"去掉,引号不存在嵌套情况。
示例1
输入:
xcopy /s c:\ d:\e
输出:
4
xcopy
/s
c:\
d:\e
法一
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
char[] ch = str.toCharArray();
boolean flag = false;
ArrayList<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < ch.length ; i++) {
if (ch[i] == '"') {
flag = flag ? false : true;
}
if (ch[i] == ' ' && !flag) {
list.add(sb.toString());
sb = new StringBuilder();
} else {
sb.append(ch[i]);
}
}
list.add(sb.toString());
System.out.println(list.size());
for (String s : list) {
System.out.println(s);
}
}
}
}