华为机试题——参数解析
来源:互联网 发布:双枪小帅的编程状态 编辑:程序博客网 时间:2024/05/29 03:13
转自https://wenku.baidu.com/view/a61815cedd88d0d232d46a48.html
题目:
在命令行输入如下命令:
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.输入由用例保证,不会出现不符合要求的输入
示例:
输入:xcopy /s c:\\ d:\\
输出:
4
xcopy
/s
c:\\
d:\\
完整代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
string s1;
vector<int> a,b;
string::size_type position=0;
const string::size_type npos = -1;
getline(cin,s1);
if (s1.find(char(34),0)!=npos) //如果存在引号
{
while(1) //先找出所有的引号
{
position=s1.find_first_of(char(34),position);
if (position==npos)
break;
a.push_back(position);
position++;
}
for (int i=0;i<a.size()-1;i+=2) //把所有引号里面的空格换成下划杠,其他的空格不变
{
string tmp=s1.substr(a[i]+1,a[i+1]-a[i]-1);
position=0;
while(1)
{
position=tmp.find_first_of(" ",position);
if (position==npos)
break;
tmp[position]='_';
position++;
}
s1=s1.replace(a[i]+1,a[i+1]-a[i]-1,tmp);
}
}
if (s1.find(' ',0)!=npos) //如果存在空格
{
position=0;
while(1) //找出所有的空格
{
position=s1.find_first_of(" ",position);
if (position==npos) break;
b.push_back(position);
position++;
}
cout<<b.size()+1<<endl; //输出参数个数
int i=0; //输出每一段参数
for (int k=0;k<b.size();k++)
{
while(i<b[k])
{
if(s1[i]==char(34))
i++;
else if(s1[i]=='_')
{
cout<<' ';
i++;
}
else if(s1[i]==' ')
i++;
else
{
cout<<s1[i];
i++;
}
}
cout<<endl;
}
for (int i=b[b.size()-1];i<s1.size();) //输出最后一段
{
if(s1[i]==char(34))
i++;
else if(s1[i]=='_')
{
cout<<' ';
i++;
}
else if(s1[i]==' ')
i++;
else
{
cout<<s1[i];
i++;
}
}
cout<<endl;
}
else //只有一段参数(没有空格)
{
cout<<"1"<<endl;
for (int i=0;i<s1.size();) //输出最后一段
{
if(s1[i]==char(34))
i++;
else if(s1[i]=='_')
{
cout<<' ';
i++;
}
else if(s1[i]==' ')
i++;
else
{
cout<<s1[i];
i++;
}
}
cout<<endl;
}
return 0;
}
- 华为机试题——参数解析
- 华为OJ——参数解析
- 华为OJ——参数解析
- 华为机试---参数解析
- 华为机试题——整数减法
- 华为机试题——字符串操作
- 华为机试题——字符串处理
- 华为机试题——正数减法
- 放苹果——华为机试题
- 指针遍历字符串—华为机试题
- 华为机试题—字符串压缩 c++
- 华为机试题—0交换排序
- 华为机试: 参数解析、 字符逆序
- 约瑟夫环—华为试题
- 华为面试题解析 - 01
- 华为面试题解析 - 02
- 华为面试题解析 - 03
- 华为面试题解析 - 04
- oracle 用户和权限
- Zigbee协议网络相关的东西(2)
- 智能指针的模拟实现
- P2P中DHT网络介绍
- Oracle截取日期格式的值
- 华为机试题——参数解析
- 思维导图--信息系统开发与管理(第一阶段)
- Spring集成rabbitMQ监听消费队列消息
- 《托马斯大学微积分》习题1.4——31
- 使用0x3f3f3f3f表示无穷大
- Spring MVC测试框架详解
- cc2640 用命令行方式烧录
- Android多媒体框架图
- http与https的区别