思路:
1、遍历, 原来的字符串长度len, 记录空格个数cnt, 则最后的字符串长度len+2*cnt。
2、从后往前遍历,遇到空格将其替换为"%20",否则原样拷贝
#include <iostream>
#include <cstring>
using namespace std;
void replace(char *c){
if(c == NULL) return;
int len = strlen(c);
if(len == 0) return;
int cnt = 0;
for(int i=0; i<len; ++i)
{
if(c[i] == ' ')
++cnt;
}
int p = len + 2*cnt;
c[p--] = '\0';//the space must be allocated first.
for(int i=len-1; i>=0; --i)
{
if(c[i] == ' ')
{
c[p--] = '0';
c[p--] = '2';
c[p--] = '%';
}
else
{
c[p--] = c[i];
}
}
}
int main(){
const int len = 100;
char c[len] = "abc def g h ";
replace(c);
cout<<c<<endl;
return 0;
}
本文介绍了一种将字符串中的空格替换为'%20'的方法。通过从后往前遍历字符串,并利用两次遍历来实现字符串的替换,这种方法可以有效地处理字符串中的空格替换问题。

被折叠的 条评论
为什么被折叠?



