C语言 字符串 查找并替换

编译环境:VS2010。

语言: C。

代码:

 

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void str_replace(char *str_src, int n, char * str_copy);

void main(void)
{
	char str_source[50] = "the book the source the end!\n";
	char str_find[10] = "the";
	char str_to_copy[10] = "+++";
	char *p;

	printf("%s", str_source);

	p = strstr(str_source, str_find);
	while(p){
		
		str_replace(p, strlen(str_find), str_to_copy);
		p = p + strlen(str_to_copy);
		p = strstr(p, str_find);
	}

	printf("%s", str_source);

}

void str_replace(char *str_src, int n, char * str_copy)
{
	int lenofstr;
	int i;
	char *tmp;
	lenofstr = strlen(str_copy); 
	//string to copy is shorter than string to find
	if(lenofstr < n)  
	{
		tmp = str_src+n;
		while(*tmp)
		{
			*(tmp-(n-lenofstr)) = *tmp; //n-lenofstr, length of moving
			tmp++;
		}
		*(tmp-(n-lenofstr)) = *tmp; //move '\0'	
	}
	else if(lenofstr > n) //string to copy longer than string to find
	{
		tmp = str_src;
		while(*tmp) tmp++;
		while( tmp>=(str_src+n) )
		{
			*(tmp+(lenofstr-n)) = *tmp;
			tmp--;
		}   
	}
	strncpy(str_src, str_copy, lenofstr);
}

测试结果:

查找字符串和替换字符串 长度相等

查找字符串的长度 小于 替换字符串的长度 

查找字符串的长度 大于 替换字符串的长度 

  • 5
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值