说明:将test.txt 中的所有“abc”替换为“ab”,替换后test.txt中将找不到完整的“abc”
打开文件,取出文本中所有的字符串到buff中,有一个数组pos记住所有要替换字符串在文本中的开始位置,使用替换算法str_replace替换所有要替换的字符串。
源程序如下:
// th.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TSIZE 10
int pos[TSIZE];//记忆替换字符串的位置
void strpos(char *find,char *str);//找到要替换字符串的在文本中所有的开始位置
char *str_replace(char *find,char *rep,char *string);//用rep替换字符串string中的find
void replace(char *fname,char *orign,char *now);//替文本中的字符串
int main(int argc, char* argv[])
{
char *fname = argv[1];
char *orign = argv[2];
char *now = argv[3];
replace(fname,orign,now);
return 0;
}
void strpos(char *find,char *str)
{//找到要替换字符串的在文本中所有的开始位置
int i,j,k,t = 1;
for (i = 0 ;i <= TSIZE ;i++)
pos[i]=0;
pos[0]=-1;
for(i = 0;str[i];i++)
{
for(j = 0,k = i;str[k] == find[j];j++,k++)
{
if(find[j+1] == '/0')
{
if(i != pos[t-1])
{
pos[t]=i;
t++;
}
}
}
}
}
char *str_replace(char *find,char *rep,char *string)
{//用rep替换字符串string中的find
int len1,len2,len3; //LEN1是要代换的字符串长度 //LEN2是代换后的长度
char *newstr; //保存新的串
int i = 0,j = 0,k = 1, count = 0,t = 0;//count记录 好替换的字符串的个数
char *p1;
char *p2;
strpos(find,string);
for(int m =1 ;m<=TSIZE;m++)
{
// printf("%d/n",pos[m]);
if(pos[m]>0)
count++;
}
len1 = strlen(rep);
len3 = strlen(find);
len2 = strlen(string)+count*(strlen(rep)-strlen(find));
newstr = (char *)malloc(len2+10);
p1 = string;
p2 = newstr;
while(*(p1+i))
{
if(i == pos[k])
{
while(*(p2+j) = *(rep+t))
{
j++;
t++;
}
t = 0;
i = i+len3;
// printf("%d次后%s j值%d/n",k,p2,j);
// printf("%d次后%s i值%d/n",k,p1,i);
k++;
}
*(p2+j) = *(p1+i);
i++;
j++;
}
*(p2+j) = '/0';
// printf("%d /n",k);
return newstr;
}
void replace(char *fname,char *orign,char *now)
{//替文本中的字符串
FILE *fp;
char *p;
char buff[500];
if((fp = fopen(fname,"r")) == NULL){
printf("不能打开文件./n");
return;
}
while(!feof(fp))
{
fgets(buff,500,fp);
}
p = (str_replace(orign,now,buff));
fclose(fp);
if((fp = fopen(fname,"w")) == NULL){
printf("不能打开文件./n");
return;
}
fputs(p,fp);
fclose(fp);
}
以上是上次写的一个,我个人觉得有很多的不成熟,请各位指正!