面試題:字符串匹配

請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。

#include <iostream>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
/**
 * @brief replaceSpace
 * @param str
 * @param length
 */
void replaceSpace(char *str,int length)
{
    int blankcount=0; //主要用於空格計數
    //遍歷原來的字符串開始進行空格計數
    for(int i=0;i<length;i++){
        if(str[i]==' '){
            blankcount++;
        }
    }
    //開始進行替換
    for(int i=length-1;i>=0;i--){
        if(str[i]!=' '){
            str[i+2*blankcount]=str[i];
        }
        if(str[i]==' '){
            blankcount--;
            str[i+2*blankcount]='%';
            str[i+2*blankcount+1]='2';
            str[i+2*blankcount+2]='0';
        }
    }
    while(*str!='\0'){
        cout<<*str;
        str++;
    }
}
int main()
{
   char *str="We Are Happy";
   int length=0;
   int i=0;
   while(str[i]!='\0'){
     length++;
     cout<<str[i];
     i++;
   }
   while(*str=='\0'){
       i=0;
       break;
   }
   cout<<endl;
   cout<<"length:"<<length<<endl;
   char *c1=new char[100];
   strcpy(c1,str);
   replaceSpace(c1,length);
   return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章