在剑指offer里面有提到这道题:Write a method to replace all spaces in a string with ‘%20’. 原因是server不能识别空格或者一些字符,所以将data send 给server前要将空格换成一些能识别字符(就像正则一样,有时候为了以后的模式识别,故意增加一些换行,---,%20之类的features,作为flag方便以后提取)。
#include <iostream>
#include <cstring>
using namespace std;
char* replace1(char* c){
if(c == NULL) return NULL;
int len = strlen(c);
if (len == 0 ) return NULL;
int cnt;
for (int i=0; i< len; ++i){
if (c[i]==' '){
++cnt;
}
}
char* cc = new char[len + 2*cnt+1];
int p=0;
for (int i=0; i < len; ++i){
if(c[i]==' '){
cc[p] = '%';
cc[p+1]='2';
cc[p+2]='0';
p += 3;
}
else{
cc[p++]=c[i];
}
}
cc[p] = '\0';
return cc;
}
int main()
{
char hw[] = "Hello World !";
cout << hw << endl;
int len = strlen(hw);
cout << len << endl;
//char hw1[] = "";
//hw1 = replace1(hw);
cout << replace1(hw)<< endl;
return 0;
}
还有另一个解法是当原来字符串足够大的时候,应该从后往前修改而不要新开一个cc[]空间。但是为什么要从后往前呢?
#include
#include
using namespace std;
char* replace1(char* c){
if(c == NULL) return NULL;
int len = strlen(c);
if (len == 0 ) return NULL;
int cnt;
for (int i=0; i< len; ++i){
if (c[i]==' '){
++cnt;
}
}
char* cc = new char[len + 2*cnt+1];
int p=0;
for (int i=0; i < len; ++i){
if(c[i]==' '){
cc[p] = '%';
cc[p+1]='2';
cc[p+2]='0';
p += 3;
}
else{
cc[p++]=c[i];
}
}
cc[p] = '\0';
return cc;
}
void replace2(char* c){
if(c==NULL) return;
int len=strlen(c);
if(len==0) return;
int cnt=0; // if not declare to 0, will cause
// segmentation fault
for (int i=0;i=0; --i){
if (c[i]==' '){
c[p]='0';
c[p-1]='2';
c[p-2]='%';
p -=3;
}
else{
c[p]=c[i];
--p;
}
}
}
int main()
{
char hw[50] = "Hello World !";
cout << hw << endl;
int len = strlen(hw);
cout << len << endl;
//char hw1[] = "";
//hw1 = replace1(hw);
cout << replace1(hw)<< endl;
char hw2[50] = "WT F !";
cout << hw << endl;
replace2(hw);
cout << hw << endl;
return 0;
}
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
Executing the program....
$demo
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
Executing the program....
$demo
Hello World ! 16 Hello%20%20%20World%20%20! Hello World ! Hello%20%20%20World%20%20!