指定字符替换

在网络编程的URL解析过程中,空格,#可能会导致网络无法正常传输,需要将其转化为相应的ASCII码,如空格的ASCII码为0X20,通常把他转为%20,下面给出相应转换代码,代码通过VS2008编译。
 
// blade.cpp : Defines the entry point for the console application.
//
#include <iostream>
char*  RePlace(const char* str="\0",char * result="\0",const char* Split=" " )//采用默认参数,你也可以输入你想要的
{
    int SpaceNum = 0;
    int N=0;
    if (str =="\0")
    {
        return result;
    }
    else
    {
        for (unsigned int i = 0;i<=strlen(str);++i)
        {
            if (str[i]==Split[0])
            {
                SpaceNum++;
            }
        }

        int N = sizeof(char)*(strlen(str)+SpaceNum*2 + 1);
        result = (char*)malloc( N );

        for (unsigned int i = 0,j=0;i<=strlen(str);i++,j++)
        {
            if(str[i]==*Split)
            {
                result[j]='%';
                result[j+1]='2';
                result[j+2]='0';
                j+=2;
            }
            else result[j]=str[i];
        }
    }
    return (char*)result;
}

int main(void)
{
    char*result="\0";
    //const char* Split = "w";//可以更改你要替换的字符
    const char * my = "my name is wang!";
    result=(char*)RePlace(my,result);
    printf("%s",result);
    system("pause");
    return 0;

}


输入:my name is wang!
输出:my%20name%20is%wang!


 

 

你可能感兴趣的:(url,字符串替换)