網絡編程中,URL鏈接可能會包含空格,可能導致服務器無法讀取確的參數,因此要對字符串進行處理,將空格替換
一般而言,特殊字符的替換規則爲:% + 十六進制的ASCII碼, 如 空格 ----> %20
對一個字符串str
1. 遍歷str1,計算空格的數量count
2.新的字符串str2的長度爲:sizeof(str1) + 2*count
3.從後面開始,把str1放到str2,若遇到空格,倒序輸入'%' '2' '0' 三個字符,然後繼續投放
實現代碼:
#include<iostream> void replace(char* a,int length){ if(a[0]=='\0'){ std::cout<<"empty string"<<std::endl; return; } int i=0,count=0; while(a[i]!='\0'){ if(a[i]==' ') count++; i++; } int len=length + 2*count; char b[len]; len--; while(i>=0 && len>=0){ if(a[i]==' '){ b[len--]='0'; b[len--]='2'; b[len--]='%'; i--; continue; } b[len]=a[i]; len--; i--; } std::cout<<b<<std::endl; } int main(){ char a[]="i love you."; std::cout<<a<<std::endl; replace(a,sizeof(a)); char b[]=" i lo ve y ou. "; std::cout<<b<<std::endl; replace(b,sizeof(b)); char c[]=""; std::cout<<c<<std::endl; replace(c,sizeof(c)); return 0; }
時間複雜度:O(n)