题目:请实现一个函数,把字符串中的每个空格替换成“%2d"。例如,请输入"We are happy",则输出”We%2dare%2dhappy“。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
char str[50] = " Hello World China!";
char *p1 = str + strlen(str) - 1;
int spaceCount = 0;
for (int i = 0; i < strlen(str); ++i)
{
if (isspace(str[i]))
spaceCount++;
}
//存储空间不够
if (strlen(str) + 2 * spaceCount > sizeof(str))
return 0;
char *p2 = p1 + 2 * spaceCount;
while (p1 >= str)
{
while (!isspace(*p1))
{
*p2 = *p1;
p1--;
p2--;
if (p1 < str)
break;
}
if (p1 < str)
continue;
*(p2--) = 'd';
*(p2--) = '2';
*(p2--) = '%';
p1--;
}
cout << str << endl;
}