c語言之strreplace字串替換
阿新 • • 發佈:2019-01-26
#include <string.h> #include <stdlib.h> #include <stdio.h> //https://github.com/ssllab/temper1/blob/722991add4a6a239271e1f029ebe4daaad719496/strreplace.c char * strreplace(char const * const original, char const * const pattern, char const * const replacement) { size_t const replen = strlen(replacement); size_t const patlen = strlen(pattern); size_t const orilen = strlen(original); size_t patcnt = 0; const char * oriptr; const char * patloc; // find how many times the pattern occurs in the original string for (oriptr = original; (patloc = strstr(oriptr, pattern)); oriptr = patloc + patlen) { patcnt++; } { // allocate memory for the new string size_t const retlen = orilen + patcnt * (replen - patlen); char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) ); if (returned != NULL) { // copy the original string, // replacing all the instances of the pattern char * retptr = returned; for (oriptr = original; (patloc = strstr(oriptr, pattern)); oriptr = patloc + patlen) { size_t const skplen = patloc - oriptr; // copy the section until the occurence of the pattern strncpy(retptr, oriptr, skplen); retptr += skplen; // copy the replacement strncpy(retptr, replacement, replen); retptr += replen; } // copy the rest of the string. strcpy(retptr, oriptr); } return returned; } } //https://github.com/CurryGuy/lua-player-plus/blob/7cb0f6056ead933289cf7dacffd6ce54243630b7/lpp-c%2B%2B/Libs/strreplace.c char *strreplace2(const char *src, const char *from, const char *to) { size_t size = strlen(src) + 1; size_t fromlen = strlen(from); size_t tolen = strlen(to); char *value = malloc(size); char *dst = value; if ( value != NULL ) { for ( ;; ) { const char *match = strstr(src, from); if ( match != NULL ) { size_t count = match - src; char *temp; size += tolen - fromlen; temp = realloc(value, size); if ( temp == NULL ) { free(value); return NULL; } dst = temp + (dst - value); value = temp; memmove(dst, src, count); src += count; dst += count; memmove(dst, to, tolen); src += fromlen; dst += tolen; } else /* No match found. */ { strcpy(dst, src); break; } } } return value; } //cl strreplace.c //gcc strreplace.c int main(int argc, char const *argv[]) { char* data=strreplace("java1024android1024cpp1024 from china ","1024","\u6765\u81ea\u4e2d\u56fd"); printf("%s\n", data); data=strreplace("java中文android中文cpp中文 from china ","中文","test"); printf("%s\n", data); char* data2=strreplace2("java1024android1024cpp1024 from china ","1024","\u6765\u81ea\u4e2d\u56fd"); printf("%s\n", data2); data2=strreplace2("java中文android中文cpp中文 from china ","中文","test"); printf("%s\n", data2); return 0; }