实现一个函数,把字符数组中的每个空格替换成“%20”。 例如输入“we are happy.”,则输出“we%20are%20happy”

#include 
#include 
int main()
{
    char a[20] = "we are happy";//数组空间要足够
    char *p = a;
    int count = 0;
    while ((*p != '\0'))
    {
        if (*p == ' ')
        {
            count++;//计算空格数
        }
        p++;
    }
    char *i = p - 1;
    char *j = i + count * 2;
    while (i <= j)
    {
        if (*i != ' ')
        {
            *j-- = *i--;
        }
        else
        {
            *j-- = '0';
            *j-- = '2';
            *j-- = '%';
            i--;
        }
    }
    printf("%s\n",a);
    system("pause");
    return 0;
}

你可能感兴趣的:(c)