python空格替换 |
您所在的位置:网站首页 › python把符号替换为空格 › python空格替换 |
记剑指offer05替换空格
问题描述 2.从后往前 需要两个数组,先计算出新数组的长度,建立新数组,同时遍历两个数组,在空格位置进行替换,其余位置直接赋值给新数组,直到遍历完原始数组。 char* replaceSpace(char* s){ if(s==NULL){ return NULL; } int i,Length=0,CountOfBlank=0; for(i=0;;i++) { if(s[i]==' '){ CountOfBlank=CountOfBlank+1; } if(s[i]=='\0'){ break; } Length++; } char *p=(char*)malloc(sizeof(char)*(Length+2*CountOfBlank+1)); if (p==NULL){ printf("内存分配不成功!\n"); } else{ int j=0; for(i=0;i p[j++]='%'; p[j++]='2'; p[j]='0'; } else{ p[j]=s[i]; } j++; } p[j]='\0'; // free(p); //return p; } return p; }二、 python 思路:由于python有插入函数,可以对字典直接进行插入,删除。可以将字符串转化为数组。 class Solution: def replaceSpace(self, s: str) -> str: s_dict = [] s_dict = list(s) for i, s_char in enumerate(s_dict): if s_char == ' ': s_dict.pop(i) s_dict.insert(i, '%20') s_str = [str(j) for j in s_dict] str2 = ''.join(s_str) return str2python相对于C简便很多。 如有不对的地方请多多指正! |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |