红联Linux门户
Linux帮助

linux c实现字符串替换

发布时间:2015-10-31 10:16:06来源:linux网站作者:linux_zhu

实现如下:

<strong><span style="font-family:KaiTi_GB2312;font-size:24px;">#include<stdio.h> 
#include<string.h> 

/* 
str_find 被搜索的字符串 
str_src 要查找的值 
str_des 替换 str_find 中的值的值 
*/ 
int str_replace(char* str_find,char* str_src, char* str_des){ 
char *ptr=NULL; 
char buff[1024]; 
char buff2[strlen(str_find)+1]; 
int i = 0; 

if(str_find != NULL){ 
strcpy(buff2, str_find); 
}
else{ 
printf("str_replace err!\n"); 
return -1;  
}

memset(buff, 0x00, sizeof(buff)); 

while((ptr = strstr( buff2, str_src)) !=0){ 
if(ptr-buff2 != 0)
memcpy(&buff[i], buff2, ptr - buff2); 
memcpy(&buff[i + ptr - buff2], str_des, strlen(str_des)); 

i += ptr - buff2 + strlen(str_des); 

strcpy(buff2, ptr + strlen(str_src)); 
}
strcat(buff,buff2); 
strcpy(str_find,buff); 
return 0; 

 
int main(int argc, char *argv[]){ 
char str[1024]={'\0'}; 
strcpy(str,argv[1]); 

str_replace(str,argv[2],argv[3]); 
printf("%s\n",str); 
return 0; 
}  </span></strong>


Linux shell字符串模式匹配运算符:http://www.linuxdiyf.com/linux/14019.html

C++字符串与转义字符:http://www.linuxdiyf.com/linux/11914.html

Linux shell字符串截取与拼接:http://www.linuxdiyf.com/linux/9890.html

UNIX/Linux下的vi/vim编辑器快速替换字符串:http://www.linuxdiyf.com/linux/10900.html

Linux下查找字符串命令:http://www.linuxdiyf.com/linux/4135.html