字符串替换空格

时间:2021-10-07 08:56:19

字符串替换空格:

请实现一个函数,把字符数组中的每个空格替换成“%20”。

例如输入“we are happy.”,则输出“we%20are%20happy.”。

 

#include <stdio.h>

#include <assert.h>

#include <windows.h>

void my_replace(char *arr, int cap)

{

         assert(arr);

         assert(cap> 0);

 

         intold_len = 0;

         intspace_nums = 0;

         char*start = arr;

         while(*start != '\0'){//"we are happy.\0"    ....[]

          if (isspace(*start)){

          space_nums++;

          }

          old_len++, start++;

         }

         intnew_len = old_len + space_nums*2+1;

         //"aa"->a%20a\0

         char*end = arr + new_len-1;

         while(start >= arr){

          if (isspace(*start)){

          *end-- = '0';

          *end-- = '2';

          *end = '%';

          }

          else{

          *end = *start;

 

          }

          start--, end--;

         }

}

 

int main()

{

         chararr[64] = "we are happy.";

         my_replace(arr,sizeof(arr)/sizeof(arr[0]));

         printf("%s\n",arr);

         system("pause");

         return0;

}