在命令行輸入如下命令:
xcopy /s c:\ d:\,
各個參數如下:
參數1:命令字xcopy
參數2:字符串/s
參數3:字符串c:\
參數4: 字符串d:\
請編寫一個參數解析程序,實現將命令行各個參數解析出來。
解析規則:
1.參數分隔符爲空格
2.對於用“”包含起來的參數,如果中間有空格,不能解析爲多個參數。比如在命令行輸入xcopy /s “C:\program files” “d:\”時,參數仍然是4個,第3個參數應該是字符串C:\program files,而不是C:\program,注意輸出參數時,需要將“”去掉,引號不存在嵌套情況。
3.參數不定長
4.輸入由用例保證,不會出現不符合要求的輸入
輸入描述:
輸入一行字符串,可以有空格
輸出描述:
輸出參數個數,分解後的參數,每個參數都獨佔一行
思路一:
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
ArrayList<String> list = new ArrayList<>();
int i = 0;
while (i < str.length())
{
char ch = str.charAt(i);
String tmp = "";
if (ch == '"')
{
i++;
while (i < str.length() && str.charAt(i) != '"')
{
tmp += str.charAt(i);
i++;
}
i++;
list.add(tmp);
tmp = "";
}
else if (ch != ' ')
{
while (i < str.length() && str.charAt(i) != ' ')
{
tmp += str.charAt(i);
i++;
}
i++;
list.add(tmp);
tmp = "";
}
}
System.out.println(list.size());
for (int j = 0; j < list.size(); j++)
System.out.println(list.get(j));
}
}
}
思路二:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String str = scanner.nextLine();
StringBuffer sb = new StringBuffer();
int count = 0;
int quota = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '\"')
quota++;
else if (str.charAt(i) != ' ')
sb.append(str.charAt(i));
else if (quota % 2 == 0)
{
sb.append('\n');
count++;
}
else
sb.append(' ');
}
System.out.println(count + 1);
System.out.println(sb.toString());
}
}
}