剑指Offer:将空格替换成20%

来源:互联网 发布:淘宝如何设置加钱换购 编辑:程序博客网 时间:2024/05/17 21:41

这里写图片描述

#define _CRT_SECURE_NO_WARNINGS 1  #include<stdio.h>  #include<stdlib.h>  #include<assert.h>  #include<ctype.h>  void My_Replace(char *arr)  {      char *start = arr;//"we are happy\0"start指向字符串首地址      char *end = NULL;      int old_len = 0;//计算代替前字符串的长度      int space_nums = 0;//空格的数目      assert(arr);//判断arr是否为空      while (*start != '\0')      {          if (isspace(*start))//如果start指向空格          {              space_nums++;          }          start++;//指向下一个元素          old_len++;      }      //start指向了字符串"we are happy\0"的\0      end = arr +old_len+ 2 * space_nums;//we%20are%20happy\0end指向\0      while (start < end )      {          if (isspace(*start))//如果start指向空格时,用%20替换空格          {              *end-- = '0';              *end-- = '2';              *end = '%';          }          else          {              *end = *start;//如果start指向的不是空格,则将字符后移          }          start--,end--;      }  }  int main()  {      char str[60] = "we are happy";      My_Replace(str);      printf("%s\n",str);      system("pause");      return 0;  }  

注:参考牛客网解决方法
这里写图片描述