替换空格_把字符串里面的空格替换成%20

#include<iostream>
#include<iomanip>
#include<list>
#include<cmath>
#include<vector>
#include<assert.h>
#include"Test.h"


void replace(char *s)  // 先计算空格总数,然后从后面开始替换,可以计算出空格后面字符的偏移量
{
    assert(s!=NULL);
    int len =strlen(s);
    int i,j;
    int x;
    for(i=0,x=0;i<len;i++) // 统计空格总数
    {
        if(s[i]==' ')
            x++;               
    }
    int spaceCount=0;
     j=len;
    for(i=len-1;i>=0;i--)
    {
        if(s[i]==' ')
        {
            spaceCount++;
            int shift=(x-spaceCount+1)*2;       // 计算偏移量
            memcpy(&s[i+1+shift],&s[i+1],j-i-1);// 要移动的位置实际是(i,j)下标之间的位置。
            memcpy(&s[i+shift-2],"%20",3); 
            j=i;                     // 
        }
    }
}
void Test()
{
    char s[100]="  We are  hap py ";
    replace(s);
    cout<<s<<endl;
}
void main()
{ 
    Test();
    system("pause");
}
原文地址:https://www.cnblogs.com/dyc0113/p/3205682.html