2空字符串替换

来源:互联网 发布:小白自学java看什么书 编辑:程序博客网 时间:2024/05/17 22:58
#include<iostream>
#include<vector>
#include<string>
#include<stack>
using namespace std;
/*****************************************************************************
请实现一个函数,将一个字符串中的空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。


总结:这个题目是有点问题的,就是字符空间变大后,申请空间的问题,这个你怎么搞,
使用malloc就可以使用变量做参数进行空间分配不能使用变量(虽然值是常数字),然
后对空间末尾添加结束标志这个题目是有点意思的,我现在才开始做题
******************************************************************************/
class solution{
public:
void replace(char*str, int length){
for (char*p = str; *p != '\0'; p++)
cout << *p;
cout << endl;
if (length <= 0 || str == NULL)
return;
int i = 0, spacenum = 0;
while (str[i] != '\0'){
if (str[i] == ' '){
spacenum++;//这里是统计多少个空字符
}
i++;//这里是统计有多少个字符,包括空字符
}
int oldlen = i;
int newlen = oldlen + spacenum * 2;
char *p = (char*)malloc(sizeof(char)*newlen);
for (i = oldlen; i >= 0; i--){
if (str[i] == ' '){
p[newlen--] = '0';
p[newlen--] = '2';
p[newlen--] = '%';
}
else{
p[newlen--] = str[i];
}
}
p[newlen] = '\0';
for (char*p1 = p; *p1 != '\0'; p1++)
cout << *p1;
cout << endl;
}
};
void main(){
char p[] = "we are happy";
solution bb;
bb.replace(p,12);
system("pause");
}
0 0