當前位置:編程學習大全網 - 編程語言 - C++編寫壹個字符串置換函數

C++編寫壹個字符串置換函數

//剛寫的code,測試通過,用C++寫的

//如果有疑問,歡迎交流

//如果source裏有多個str_s字串,那麽都會將其替換掉

//這裏的條件邏輯,可能有點兒復雜,設定壹些狀態,用flag表示

//flag:?0表示要往tmp_source裏插入字符

//flag:?1表示當前找到了可能是str_s的字串

#include<iostream>

#include<string>

using?namespace?std;

#define?N?1000

void?repstr(char?*?source,?char?*?str_s,?char?*?str_d){

int?src_len?=?strlen(source);

char?*tmp_source?=?new?char[N];?//創建壹個新串,保存替換後的結果

int?flag?=?0;

int?cur_idx?=?0,?str_d_idx?=?0,?str_s_idx?=?0,?tmp_idx?=?0;

while(source[cur_idx]?!=?'\0'){

if(flag?==?0?&&?source[cur_idx]?==?str_s[0]){

flag?=?1;

str_s_idx++;

cur_idx++;

}

if(flag?==?1){

if(str_s[str_s_idx]?==?'\0'){

str_d_idx?=?0;

//

while(str_d[str_d_idx]!='\0'){

tmp_source[tmp_idx]?=?str_d[str_d_idx];

tmp_idx++;

str_d_idx++;

}

str_s_idx?=?0;

flag?=?0;

}else?if(str_s[str_s_idx]?==?source[cur_idx]){

str_s_idx++;

cur_idx++;

}else?if(str_s[str_s_idx]?!=?source[cur_idx]){

flag?=?0;

cur_idx?=?cur_idx?-?str_s_idx;

str_s_idx?=?0;

}

}

if(flag?==?0&&source[cur_idx]!='\0'){

tmp_source[tmp_idx]?=?source[cur_idx];

tmp_idx++;

cur_idx++;

}

}

tmp_source[tmp_idx]?=?'\0';

tmp_idx?=?0;

while(tmp_source[tmp_idx]!='\0'){

source[tmp_idx]?=?tmp_source[tmp_idx];

tmp_idx++;

}

source[tmp_idx]?=?0;

delete?tmp_source;

}

int?main(){

char?source[1000]?=?"word?hellonicehelotoyouhellowhy";

cout<<source<<endl;

char?*src_s?=?"hello";

char?*tar_s?=?"ChinaFootball";

repstr(source,?src_s,?tar_s);

cout<<source<<endl;

return?0;

}

  • 上一篇:怎樣報考CEAC計算機輔助設計工程師
  • 下一篇:渲染常識基礎
  • copyright 2024編程學習大全網