设为首页 - 加入收藏 焦点技术网
热搜:java
当前位置:首页 >

C语言字符串替换函数,字符串插入函数的实现

2013-04-23 19:59:00.0 学习C/C++经验  
导读://字符串替换函数,在字符串 string 中查找 source, 找到则替换为destination,找不到则返回NULLstatic char * replace_string (char * string, const char * source, const char * destination ){ char* sk = strstr (string, source); if (sk =...。。。

//字符串替换函数,在字符串 string 中查找 source, 找到则替换为destination,找不到则返回NULLstatic char * replace_string (char * string, const char * source, const char * destination ){ char* sk = strstr (string, source); if (sk == NULL) return NULL; char* tmp; size_t size = strlen(string)+strlen(destination)+1; char* newstr = (char*)calloc (1, size); if (newstr == NULL) return NULL; char* retstr = (char*)calloc (1, size); if (retstr == NULL) {  free (newstr);  return NULL; }  snprintf (newstr, size-1, "%s", string); sk = strstr (newstr, source); while (sk != NULL) {  int pos = 0;  memcpy (retstr+pos, newstr, sk - newstr);  pos += sk - newstr;  sk += strlen(source);  memcpy (retstr+pos, destination, strlen(destination));  pos += strlen(destination);  memcpy (retstr+pos, sk, strlen(sk));  tmp = newstr;  newstr = retstr;  retstr = tmp;  memset (retstr, 0, size);  sk = strstr (newstr, source); } free (retstr); return newstr;}//字符串插入函数  在字符串string 中查找 source , 找到后再 source之后插入字符串 destination, 找不到则返回 NULLstatic char * insert_string (char * string, const char * source, const char * destination ){ char* sk = strstr (string, source); if (sk == NULL) return NULL; char* tmp; size_t size = strlen(string)+strlen(destination)+1; char* newstr = (char*)calloc (1, size); if (newstr == NULL) return NULL; char* retstr = (char*)calloc (1, size); if (retstr == NULL) {  free (newstr);  return NULL; }  snprintf (newstr, size-1, "%s", string); sk = strstr (newstr, source); int pos = 0; sk += strlen(source); memcpy (retstr+pos, newstr, sk - newstr); pos += sk - newstr; memcpy (retstr+pos, destination, strlen(destination)); pos += strlen(destination); memcpy (retstr+pos, sk, strlen(sk)); free (newstr); return retstr;}


(编辑: langeldep)

网友评论
相关文章