1. 程式人生 > >實現字串的查詢和替換

實現字串的查詢和替換

在字串中查詢目標字串並將其替換為指定字串,返回替換的次數。介面為

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_str
void 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;
}