#include <iostream>
using namespace std;
void replaceBlack(char str[], int length)
{
if (str==nullptr || length<=0)
{
cout << "请输入正确的字符串!" << endl;
return;
}
int originalLen = 1;
int blackNum = 0;
char *p1 = &str[0];
while (*p1!='\0')
{
if (*p1==' ')
{
blackNum++;
}
p1++;
originalLen++;
}
int newLength = originalLen + blackNum * 2;
if (newLength>length)
{
cout << "超出了数组的大小!" << endl;
return;
}
char *p2 = str + (newLength-1);
p1 =&str[originalLen-1];
while (p1!=str)
{
if (*p1!=' ')
{
*p2 = *p1;
p1--;
p2--;
}
else
{
*p2 = '0';
*(--p2) = '2';
*(--p2) = '%';
p1--;
p2--;
}
}
}
int main(void)
{
char a[40] = "We are happy.";
replaceBlack(a, 40);
cout << a << endl;
system("pause");
return 0;
}
剑指Offer 第五题 替换空格
最新推荐文章于 2021-02-21 16:25:08 发布