64,643
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<cstring>
#define MAX_CAPACITY 100
using namespace std;
class Replace
{
public:
void ReplaceSpace(char *str)
{
if (str == NULL)
{
return;
}
int length = strlen(str) + 1;
int newLength = 0;
int numOfBlank = 0;
/*while (*str != '\0')
{
if (*str == ' ')
{
numOfBlank++;
}
*str++; 此处改变了str的位置,显然错误!!!
}*/
int i = 0;
while (str[i] != '\0')
{
if (str[i] == ' ')
{
numOfBlank++;
}
i++;
}
newLength = length + numOfBlank * 2;
while (length >= 0)
{
if (str[length] == ' ')
{
str[newLength--] = '0';
str[newLength--] = '2';
str[newLength--] = '%';
}
else
{
str[newLength--] = str[length];
}
--length;
}
return;
}
};
void main()
{
char str1[] = "we are happy!";
Replace r;
r.ReplaceSpace(str1);
cout << str1 << endl;
}