本文共 961 字,大约阅读时间需要 3 分钟。
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。代码实现如下:
class Solution { public: void replaceSpace(char *str,int length) { if(str==NULL||length<=0) return; int old_length=0;//字符串实际长度 int Blank_Number=0;//有多少个空格 int i=0; while(str[i]!='\0') { ++old_length; if(str[i]==' ') ++Blank_Number; ++i; } //空格转换为%20之后新的字符串长度 int new_length=old_length+2*Blank_Number; if(new_length>length) return; int indexO=old_length; int indexN=new_length; while(indexO>=0 && indexN>indexO ) { if(str[indexO]==' ') { str[indexN--]='0'; str[indexN--]='2'; str[indexN--]='%'; } else { str[indexN--]=str[indexO]; } --indexO; } }};
转载地址:http://cxuoi.baihongyu.com/