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

在剑指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
     
     
    
    
   
   
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  !
16
Hello%20%20%20World%20%20!
Hello   World  !
Hello%20%20%20World%20%20!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值