描述
在命令行输入如下命令:
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,注意输出参数时,需要将""去掉,引号不存在嵌套情况。
3.参数不定长
4.输入由用例保证,不会出现不符合要求的输入
数据范围:字符串长度:1≤s≤1000
进阶:时间复杂度:O(n) ,空间复杂度:O(n)
输入描述:
输入一行字符串,可以有空格
输出描述:
输出参数个数,分解后的参数,每个参数都独占一行
示例1
输入:
xcopy /s c:\\ d:\\e
输出:
4 xcopy /s c:\\ d:\\e
#include<cstdio>
#include<string>
#include<vector>
using namespace std;
int main()
{
// 0.读取数据
char buf[2000];
fgets(buf,2000,stdin);
string str=buf;
str.pop_back(); //去掉fgets多读的换行符
str.push_back(' '); //字符串最后补充一个空格最为结束
// 1.处理
string temp="";
int count=0; // 统计参数
vector<string> answer; //存放提取出的参数
for(int i=0;i<str.size();i++)
{
// 1.1 不是空格
if(str[i]!=' ')
{
temp.push_back(str[i]);
}
// 1.2 是空格,有3种可能情况
else{
// 1)已收集的字符串非引号包含
if(temp[0]!='"' && temp[temp.size()-1]!='"')
{
count++;
answer.push_back(temp);
temp="";
continue;
}
// 2)引号内的空格
else if(temp[0]=='"' && temp[temp.size()-1]!='"')
{
temp.push_back(str[i]);
}
// 3)已收集的字符串用引号包含
else if(temp[0]=='"' && temp[temp.size()-1]=='"')
{
count++;
answer.push_back(temp);
temp="";
continue;
}
}
}
// 2.输出
printf("%d\n",count);
for(int i=0;i<answer.size();i++)
{
string str=answer[i];
if(str[0]=='"' && str[str.size()-1=='"'])//用引号包含的参数,输出时去掉引号
{
printf("%s\n",str.substr(1,str.size()-2).c_str());
}
else {
printf("%s\n",answer[i].c_str());
}
}
}