您的位置:首页 > 其它

替换空格

2015-09-03 16:41 323 查看


题目描述(牛客网)

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: