str_replace for C

PS  靠 刚测试了下  这东西 不好使啊 

自己搞定了个 
char *str_replace(const char *search ,const char *replace ,const char *subject)
{
    int i = 0;
    char *str = strdup(subject);
    char *p = str;
    char *new_str;
    char *p1;
    int len = strlen(str);
    while((p = strstr(p,search)))
    {
        *p = '\0';
        p+=strlen(search);
        ++i;
    }
    if(i < 1)
    {
        free(str);
        return NULL;
    }
    new_str = (char *)malloc(i * strlen(replace) + strlen(subject));
    *new_str = 0;
    p1 = new_str;
    p = str;
    for (p = str;(int)p - (int)str < len;)
    {
        if(*p == '\0')
        {
            strcat(p1,replace);
            p += strlen(search);
            p1 += strlen(replace);
        }
        else
        {
            *p1++ = *p++;
            *p1 = 0;
        }
    }
    free(str);
    return new_str;
}

//

http://www.binarytides.com/str_replace-for-c/
Php has a useful function called str_replace which can search and 
replace a certain string in another big string. However there is no such
 function in C. So I wrote up one for myself. Here is the code.

/*
 * Search and replace a string with another string , in a string
 * */
char *str_replace(char *search , char *replace , char *subject)
{
	char  *p = NULL , *old = NULL , *new_subject = NULL ;
	int c = 0 , search_size;
	
	search_size = strlen(search);
	
	//Count how many occurences
	for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
	{
		c++;
	}
	
	//Final size
	c = ( strlen(replace) - search_size )*c + strlen(subject);
	
	//New subject with new size
	new_subject = malloc( c );
	
	//Set it to blank
	strcpy(new_subject , "");
	
	//The start position
	old = subject;
	
	for(p = strstr(subject , search) ; p != NULL ; p = strstr(p + search_size , search))
	{
		//move ahead and copy some text from original subject , from a certain position
		strncpy(new_subject + strlen(new_subject) , old , p - old);
		
		//move ahead and copy the replacement text
		strcpy(new_subject + strlen(new_subject) , replace);
		
		//The new start position after this search match
		old = p + search_size;
	}
	
	//Copy the part after the last search match
	strcpy(new_subject + strlen(new_subject) , old);
	
	return new_subject;
}

转载于:https://my.oschina.net/sincoder/blog/95300

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值