把字符串中的每个空格替换成“%20”.
eg:we are happy—->we%20are%20happy
#include <iostream>
using namespace std;
#define MAX 50
void ReplaceBlank(char arr[],int len)
{
assert(arr != NULL);
int blanknum = 0;//空格个数
int oldnum = 0;//字符串长度
//遍历一遍,求出空格的个数
for(int i=0;arr[i]!='\0';i++)
{
oldnum++;
if(isspace(arr[i]))
{
blanknum++;
}
}
//从后向前替换
int newlen = oldnum + blanknum*2;
if(newlen > len)
return;
int i = newlen;
int j = oldnum;
while(i>=0 && i>j)
{
if(isspace(arr[j]))
{
arr[i--] = '0';
arr[i--] = '2';
arr[i--] = '%';
}
else
{
arr[i--] = arr[j];
}
--j;
}
for(int i=0;arr[i]!='\0';i++)
{
cout<<arr[i]<<ends;
}
cout<<endl;
}
int main()
{
char arr[MAX] = "we are happy!";
ReplaceBlank(arr,MAX);
return 0;
}