实现字符串的查找和替换

来源:互联网 发布:影像测量仪软件 编辑:程序博客网 时间:2024/06/06 08:40

在字符串中查找目标字符串并将其替换为指定字符串,返回替换的次数。接口为

int find_str_replace(char *&str,const char *find_str,const char *replace_str)

将str中所有find_str替换为replace_str。要求不利用STL,c实现代码如下:

#include<stdio.h>#include<string.h>#include<stdlib.h>//查找str从fromwhere开始第一次出现sub_str的位置int find(const char *str,const char *sub_str,int fromwhere){int len=strlen(str);int len_f=strlen(sub_str);for(int i=fromwhere;i<len&&len-i>=len_f;i++){int k=i;int j=0;while(j<len_f){if(str[k]==sub_str[j]){k++;j++;}else    break;}if(j==len_f){return i;}}return -1;}//替换fromwhere处的find_str为replace_strvoid replace(char *&str,const char *find_str,const char *replace_str,int fromwhere){int len=strlen(str);int len_f=strlen(find_str);int len_r=strlen(replace_str);char *p=(char*)malloc(len+len_r-len_f);memset(p,0,len+len_r-len_f);strncpy(p,str,fromwhere);strcat(p,replace_str);strcat(p,str+fromwhere+len_f);str=p;}//在str中将所有find_str替换为repalce_str;int find_str_replace(char *&str,const char *find_str,const char *replace_str){int num=0;int len=strlen(str);int len_r=strlen(replace_str);int k=0;while(k<len){int pos=find(str,find_str,k);if(pos==-1)break;else{replace(str,find_str,replace_str,pos);k=pos+len_r;num++;}}return num;}int main(){char *a="123456783450987634243453";char *b="345";char *c="ABCD";int num=find_str_replace(a,b,c);printf("%s\n",a);printf("%d",num);return 0;}
若使用c++并利用STL,代码极其简单:

#include<iostream>#include<string>using namespace std;int find_str_replace(string &str,string find_str,string replace_str){int num=0;int len_f=find_str.length();int len_r=replace_str.length();int pos=str.find(find_str,0);while(pos!=string::npos){  str.replace(str.begin()+pos,str.begin()+pos+len_f,replace_str);  pos=pos+len_r;  pos=str.find(find_str,pos);  num++;}return num;}int main(){string a="123456783450987634243453";string b="345";string c="ABCD";int num=find_str_replace(a,b,c);printf("%s\n",a.c_str());printf("%d",num);return 0;}



0 0
原创粉丝点击