题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
我的编程思想是先统计空格个数blankCount,由此算出替换后的字符串长度tLength,后来通过下标从后面往前面替换,这样遇到空格插入%20,否则将字符后移。
我的程序:
class Solution {
public:
void replaceSpace(char *str,int length) {
int blankCount = 0, i = 0;
while(str[i] != NULL) {
if(str[i++] == ' ') {
blankCount++;
}
}
int tLength = blankCount * 2 + length;
int j = 0;
for(i = 0; i <= length; i++) {
if(str[length - i] == ' ') {
str[tLength - j++] = 48;
str[tLength - j++] = 50;
str[tLength - j++] = '%';
}
else {
str[tLength - j++] = str[length - i];
}
}
}
};
显示结果:
运行错误,你提交的程序运行时发生错误。
自查了半天好像没有溢出什么的。。。