#include "iostream"
#include <string>
using namespace std;
%length为字符数组p的总容量
void replaceBlank(char *p,int length)
{
if (p == NULL || length <= 0)
return;
int blankNum = 0;
int originalLength = 0;
int i = 0;
while (p[i]!='\0')
{
++originalLength;
if (p[i] == ' ')
++blankNum;
++i;
}
int newLength = originalLength + blankNum * 2;
if (newLength > length)
return;
int indexoforiginal = originalLength-1;
int indexofNew = newLength-1;
while (indexoforiginal>=0&&indexofNew>indexoforiginal)
{
if (p[indexoforiginal] == ' ')
{
p[indexofNew--] = '0';
p[indexofNew--] = '2';
p[indexofNew--] = '%';
}
else
{
p[indexofNew--] = p[indexoforiginal];
}
indexoforiginal--;
}
}
int main()
{
char c[13] = { "ka ha ha" };
replaceBlank(c, 13);
system("pause");
return 0;
}
剑指offer面试题4:替换空格
最新推荐文章于 2024-02-27 18:26:29 发布