字符串操作之替换字符

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/simonyucsdy/article/details/82694309

 要求:将一个字符串中的所有空格替换成%20字符串。

思路:难点在于,空格只占用一个字符,而%20要占用三个。所以简单的字符替换肯定达不到要求,只能从其他角度来思考:替换以后的字符串长度发生了改变,那么最好的的办法就是先知道操作完成后的字符串长度。然后再从后往前的遍历字符串,将费空格的字符移动到后面,遇到空格则用%20来填补。

//将字符串中的空格替换成为%20

#include <iostream>
#include <string.h>
using namespace std;

void replace(char str[])
{
    if(!strlen(str))
        return;

    int len = strlen(str);
    char *p1 = str + len - 2;

    char *p = str;
    while(*p)
    {
        if(*p == ' ')
        {
            len += 2;
        }
        p++;
    }

    char *p2 = str + len - 2;

    while(p1 >= str && p2 > p1)
    {
        if(*p1 == ' ')
        {
            *p2-- = '0';
            *p2-- = '2';
            *p2-- = '%';
        }
        else
        {
            *p2-- = *p1;
        }
        p1--;
    }
}

int main()
{
    char str[] = "Hello World I Am A Programer!";
    replace(str);

    cout << str << endl;


    return 0;
}

运行结果:

                            

猜你喜欢

转载自blog.csdn.net/simonyucsdy/article/details/82694309