题目:
请实现一个函数,把字符中的每个空格替换成“%20”。例如输入
“we are happy”则输出 “we%20are%20happy."。
解题思路:
-
-
w |
e |
% |
2 |
0 |
a |
r |
e |
% |
2 |
0 |
h |
a |
p |
p |
y |
/* length 为string数组的容量*/
void replaceSpace(char string[] length ){
if(string==NULL|| length <=0)
return;
int originalLength = 0;//统计字符串个数;
int numberBlank = 0; //统计空格数;
int i =0;
while(str[i] != '\0'){
if(str[i] == ' '){
++numberBlank;
}
++originalLength;
++i;
}
int newLength = originalLength + numberBlank * 2;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
if(newLength>length)
return;
where(indexOfOriginal >= 0 && indexOfNew >indexOfOriginal){
if(string[indexOfOriginal] == ' '){
string[New--] = '0';
string[New--] = '2';
string[New--] = '%';
}else{
string[New--] = string[indexOfOriginal];
}
--indexOfOriginal;
}
}
网友评论