替换空格

来源:互联网 发布:占领中环 知乎 编辑:程序博客网 时间:2024/05/18 07:36

题目描述(牛客网)

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

  • 时间限制:1秒空间限制:32768K
  • 通过比例:19.30%
  • 最佳记录:0 ms|8552K
实现代码:


void replaceSpace(char *str,int length) {        int num = 0;        for(int i = 0;i < length;i++){            if(str[i] == ' ')                num++;        }        for(int i = length;num > 0;i--){            if(str[i] != ' '){                str[i + 2*num] = str[i];            }            else{                str[i + 2*num] = '0';                str[i + 2*num - 1] = '2';                str[i + 2*num - 2] = '%';                num--;            }        }}

注意:使用数组,不要轻易使用指针,容易出错

在老版本的VC上要用到辅助空间才行,不然自动判定数组越界

老版VC代码:

#include <iostream>using namespace std;void replaceSpace(char *str,int length) {        int num = 0;        for(int j = 0;j < length;j++){            if(str[j] == ' ')                num++;        }cout << num;char *a = new char[length+2*num +1];     //申请辅助空间,连同'\0'一起搬运,所以要加1;        for(int i = length;i >= 0;i--){            if(str[i] != ' '){                a[i + 2*num] = str[i];            }            else{                a[i + 2*num] = '0';                a[i + 2*num - 1] = '2';                a[i + 2*num - 2] = '%';                num--;            }        }       cout << a << endl;    delete a;}int main(){char *str = "hello world s k q";    replaceSpace(str,17);}


0 0