#include <iostream>
using namespace std;
void ReplaceBlank(char str[], int length)
{
if(str == NULL || length<=0)
return;
int originalLength = 0;
int numofBlank = 0;
int i = 0;
//计算原字符串的长度,并统计空格个数
while(str[i]!= '\0')
{
originalLength ++;
if(str[i] == ' ')
numofBlank ++;
i++;
}
//每替换一个空格,长度增加2
int newlength = originalLength + numofBlank * 2;
if(newlength>length)
return;
int indexofOriginal = originalLength;
int indexofNew = newlength;
while(indexofOriginal>=0 && indexofNew>indexofOriginal)
{
if(str[indexofOriginal]==' ')
{
str[indexofNew--]='0';
str[indexofNew--]='2';
str[indexofNew--]='%';
}
else
str[indexofNew--]=str[indexofOriginal];
indexofOriginal--;
}
}
int main()
{
char str[]="hello world hello c++";
ReplaceBlank(str,100);
cout << "result is "<< str<<endl;
return 0;
}
转载于:https://www.cnblogs.com/geekvc/p/6657322.html