4--替换空格

/*
题目要求:
    替换空格。
    we are happy。
    we%20are%20happy。


算法解析:
    字符串长度为14.
    先计算有多少个空格,测试字符串为2个。这样总长度为18.
    从最后一个字符向后移动,注意控制指针,空格是1个字符,%20是三个。


*/


#include <stdio.h>

void replaceStr(char str[])
{
    int count_space = 0;
    int str_length = 0;
    for (int i = 0; str[i] != '\0'; i++)
    {
        if (str[i] == ' ')
            count_space++;
        str_length++;
    }
//    printf("%d\n",count_space);

    int p1 = str_length;
    int p2 = str_length + count_space * 2;
    printf("%d, %d\n", p1, p2);

    while (p1 != p2 || p1 < 0)
    {
        while (str[p1] != ' ')
        {
            str[p2--] = str[p1--];
        }

        str[p2--] = '0';
        str[p2--] = '2';
        str[p2--] = '%';

        p1--;
    }

}

int main()
{
    char str[30] = "we are happy.";
    replaceStr(str);

    printf("%s\n", str);
    return 0;
}

 

posted on 2015-09-27 18:52  HGonlyWJ  阅读(203)  评论(0编辑  收藏  举报

W3C中国
阮老师的网络日志
canvas
runoob
迷渡
并发编程网
原生JS例子
前端外刊评论