生活会辜负努力的人,但不会辜负一直努力的人

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
void replaceSpace(char *str, int length) {

    int spaceNum = 0;
    int len = strlen(str);
    for (int i = 0; i < len; i++) if (str[i] == ' ') spaceNum++;

    const int N = len + 1 + spaceNum * 2;
    char *s = (char*)malloc(sizeof(char)*N);

    while (*str) {
        if (*str != ' ') {
            *s = *str;
            s++;
        }
        else {
            strcpy(s, "%20");
            s = s + 3;
        }
        str++;
    }
    *s = '\0';
    s = s - N + 1;
    str = str - len;
    strcpy(str, s);
}

 

posted on 2018-09-14 22:48  何许亻也  阅读(189)  评论(0编辑  收藏  举报