【牛客】[编程题]参数分析C++

1.题目描述

链接:https://www.nowcoder.com/questionTerminal/668603dc307e4ef4bb07bcd0615ea677?toCommentId=128167

在命令行输入如下命令:

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.输入由用例保证,不会出现不符合要求的输入

2.思路分析

  1. 先循环出入字符串
  2. 利用for循环来计数空格的数量
  3. 最后打印count(这个count一定是比空格的数量要大1)
  4. 第二次循环就是打印字符串
  5. 先给一个flag来判断是不是在双引号里面
  6. 如果在的话那就直接打印空格
  7. 不在的话就换行
  8. 其他情况就直接打印字符

3.代码实现

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str;
	while (getline(cin, str))
	{
		// 计数空格的数量
		int count = 0;
		for (int i = 0; i < str.size(); i++)
		{
			if (str[i] == ' ')
				count++;
			if (str[i] == '"')
			{
				do{
					i++;
				} while (str[i] != '"');
			}
		}
		// 参数的个数一定比空格多1
		cout << count + 1 << endl;

	    int flag = 1;
	    for (int i = 0; i < str.size(); i++)
     	{
		    // 如果是“的话就flag置为0
		    if (str[i] == '"')
			    flag ^= 1;

		    // 不是空格和双引号直接打印
		    if (str[i] != ' ' && str[i] != '"')
			    cout << str[i];

		    // 不在双引号内的空格直接换行
		    if (str[i] == ' ' && (flag))
			    cout << ' ' << endl;

		    // 双引号内的空格直接打印
		    if (str[i] == ' ' && (!flag))
			    cout << str[i];
	    }
    }
	cout << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43967449/article/details/106758468