【编程题】替换空格,在线测试系统显示程序异常退出

题目描述

请实现一个函数,将一个字符串中的空格替换成“%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];
            }
        }
    }
};

显示结果:
运行错误,你提交的程序运行时发生错误。

自查了半天好像没有溢出什么的。。。

http://www.xuebuyuan.com/1410069.html

溢出了,应该再减1.........

因为要将一个空格字符换成 %20 是三个字符,所以需要重新分配空间。否则,如果保证原字符串的空间是足够的,来放修改后的、变长的字符串。

1楼
综合上面链接的内容,发现void replaceSpace(char *str,int length)中的length变量应该不代表字符串实际长度(实际长度不包含NULL结束符),在第十行添加int l = i,并把之后的length变量全部改成 l 变量,结果系统提示运行正常且答案正确
但是问题来了,那length到底代表什么呢?如果是字符串空间总长度的话,那我不加if(tLength > length) return 1;的判定结果也没出错啊,这是一个void函数不能加return语句

修改后的代码:

 class Solution {
public:
    void replaceSpace(char *str,int length) {
        int blankCount = 0, i = 0;
        while(str[i] != NULL) {
            if(str[i++] == ' ') {
                blankCount++;
            }
        }
        int l = i;
        int tLength = blankCount * 2 + l;
        int j = 0;
        for(i = 0; i <= l; i++) {
            if(str[l - i] == ' ') {
                str[tLength - j++] = 48;
                str[tLength - j++] = 50;
                str[tLength - j++] = '%';
            }
            else {
                str[tLength - j++] = str[l - i];
            }
        }
    }
};

系统返回结果:
答案正确:恭喜!您提交的程序通过了所有的测试用例