字符串替换, src 源字符串, buf_size 缓冲大小, search搜索的字符串大小, repstr 需要替换成的字符串
int str_replace(char *src, unsigned int buf_size, char* search, char *repstr) { if(!src || !search || !repstr|| buf_size < 0) { return -1; } const unsigned int size = buf_size + 1024 ; char * temp = (char *)malloc(size); memset(temp, 0x00, size); char * src_pos = src; char * result = src; char * dst_pos = temp; unsigned int length = 0; int search_len = strlen(search); int rep_len = strlen(repstr); do { src_pos = strstr(src_pos, search); if(!src_pos) { strcpy(dst_pos, result); length += search_len; break; } strncpy(dst_pos, result, src_pos - result); dst_pos += src_pos - result; //replace strcat(dst_pos, repstr); dst_pos += rep_len; length += src_pos - result + rep_len; src_pos += search_len; result = src_pos; } while(src_pos); if(length >= buf_size) { free(temp); temp = NULL; return -1; } else { _snprintf_c(src,buf_size,"%s", temp); free(temp); temp = NULL; return 0; } } int main(void) { char buf[512] ={"123%4235%%6723"}; printf("%s ", buf); str_replace(buf,512,"%","love"); printf("%s ", buf); return 0; }
结果输出:
123%4235%%6723
123love4235lovelove6723