Ch1-5: Write a method to replace all spaces in a string with ‘%20’.

来源:互联网 发布:php substr函数 编辑:程序博客网 时间:2024/05/17 05:51

在剑指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[]空间。但是为什么要从后往前呢?

Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo 
Hello   World  !16Hello%20%20%20World%20%20!Hello   World  !Hello%20%20%20World%20%20!


0 0