⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 串的replace函数.cpp

📁 串的Replace函数
💻 CPP
字号:
// 串的Replace函数.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define MAX  100


typedef struct{

	char ch[MAX];

	int len;
}seqstring;

int index_b(seqstring *s,seqstring *t)    //找到子串的位置
{
      int i = 0, j = 0;

      while(i < s->len && j < t->len)

            if(s->ch[i]==t->ch[j])
                  {i++; j++;}
            else
            {i = i - j + 1;
             j = 0;}
      if(j >= t->len)

         return i - t->len+1;
      
	  else
            return 0;
}

seqstring * createString(char *s){     //创建顺序串

	int n;

	n=strlen(s);

	seqstring *ss;

	ss=(seqstring *)malloc(sizeof(seqstring));

	strcpy(ss->ch,s);

	ss->len=n;

	return ss;
}

seqstring * Replace(char *s,char *t,char *v){    //Replace函数

    seqstring *ss,*ts;

	char temp[MAX];

	ss=createString(s);

	ts=createString(t);

	int index,i=0,in;      //index为在主串的第一个子串的位置

	while((index=index_b(ss,ts))!=0){

		in=index+ts->len-1;

		i=0;

		while(ss->ch[in]!='\0'){  //用一个临时数组存放第一个子串后面的的字符串

			temp[i]=ss->ch[in];

			i++;

			in++;
		}
		temp[i]='\0';

		in=index-1;

		while(ss->ch[in]!='\0'){   //清空

			ss->ch[in]='\0';

			in++;
		}
	
		strcat(ss->ch,v);       //两次连接,完成一趟替换

		strcat(ss->ch,temp);

		ss->len=strlen(ss->ch);  //len值也要相应的变化
	}

	return ss;

}

void display(seqstring *s){   //打印函数

	printf("%s\n",s->ch);
}




void main(){

	char s[]="bbabbabba";

	char t[]="b";

	char v[]="c";

	seqstring *ss;

	ss=(seqstring *)malloc(sizeof(seqstring));

	ss=Replace(s,t,v);

	display(ss);
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -