描述
在命令行输入如下命令:
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\le s\le 1000\1≤s≤1000
进阶:时间复杂度:O(n)\O(n) ,空间复杂度:O(n)\O(n)
输入描述:
输入一行字符串,可以有空格
输出描述:
输出参数个数,分解后的参数,每个参数都独占一行
示例1
输入:
xcopy /s c:\\ d:\\e
复制输出:
4 xcopy /s c:\\ d:\\e
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>
void print(std::vector<std::string> strVect)
{
for (int i = 0; i < strVect.size(); ++i)
{
std::cout << strVect.at(i) << std::endl;
}
}
void paragramAnalysis(std::string str)
{
// std::string str = R"srcstr";
// std::cout << "str=" << str << std::endl;
std::vector<std::string> rtnVect; //存放解析出的命令
//逐个扫描每个字符.如果是双引号,则将mark改为true,遇到下一个双引号则该为false,截取双引号之间的字符串,此时忽略空格
bool mark = false;
int markLeft = 0;
int markRight = 0;
int i = 0;
while (i < str.length())
{
if (str[i] == '"')
{
mark = true;
markLeft = i;
}
if (mark == false) //此时碰到空格则截取
{
if (str[i] == ' ' || i == str.length() - 1)
{ // 012345678
std::string temp = str.substr(0, i + 1); // "12345" 543 9
if (temp != " ")
{
rtnVect.push_back(temp);
}
str = str.substr(i + 1, str.length() - i - 1);
i = 0;
}
else
{
i++;
}
}
else //处理含有双引号的字符串
{
i++;
while (i < str.length())
{
if (str[i] == '"')
{
std::string temp = str.substr(markLeft + 1, i - markLeft - 1); // 12345 543 9
if (temp != " ")
{
rtnVect.push_back(temp);
}
str = str.substr(i + 1, str.length() - i - 1);
mark = false;
i = 0;
break;
}
i++;
}
}
}
std::cout << rtnVect.size() << std::endl;
print(rtnVect);
}
int main()
{
std::string str;
getline(std::cin, str);
paragramAnalysis(str);
return 0;
}