字符串中空格的替换

版权声明: https://blog.csdn.net/if_i_were_a/article/details/82428145

《剑指offer》p51

/*
面试题5替换空格: 请实现一个函数,把字符串中的每个空格替换成20%。例如“We are happy”
则输出“We%20are%20happy” 
*/
#include<stdio.h>
void stringReplace(char str1[])
{
    int i,j;
    int originLength,newLength=0;
    int spaceNum=0;
    int p1=0,p2=0;
    for(i=0;str1[i]!='\0';originLength++,i++);
    for(j=0;j<originLength;j++)
    {
        if(str1[j]==' ')
        spaceNum++;
    }
    newLength=originLength+spaceNum*2;
    p1=originLength;
    p2=newLength;
    while(p1!=p2)
    {
        str1[p2]=str1[p1];
        if(str1[p1]==' ')
        {
            str1[p2--]='0';
            str1[p2--]='2';
            str1[p2--]='%';    
        }
        else
        {
            p2--;
        }    
        p1--;
    }
}
int main (void)
{
    char str1[100];
    printf("请输入一个字符串");
    gets(str1);
    stringReplace(str1);
    puts(str1);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/if_i_were_a/article/details/82428145
今日推荐