机试练习7.11

xiaoxiao2021-02-28  79

题目描述 请实现一个函数,将一个字符串中的空格替换成“ ”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We Are Happy。 思路:没有什么比较好的办法,首先将字符串遍历一遍, 找出字符串中的空格数,从后往前再次遍历字符串,同时将字符后移,这样省空间。

class Solution { public: void replaceSpace(char *str,int length) { int cnt=0; for(int i=0;i<length;i++) { char c=str[i]; if(c==' ') { cnt++; } } if(cnt!=0) { for(int i=length-1;i>=0;) { char c=str[i]; if(c!=' ') { str[i+2*cnt]=str[i]; i--; } else { cnt--; str[i+2*cnt]='%'; str[i+2*cnt+1]='2'; str[i+2*cnt+2]='0'; i--; } } } } };
转载请注明原文地址: https://www.6miu.com/read-77368.html

最新回复(0)