-
1 # 偷懶的蜜蜂
-
2 # 偷懶的蜜蜂
/* 功能:查詢替換函式 返回值:替換後的字串 strretu */char *Replace(char *str, char *str1, char *str2, char *strretu){ char *str_temp = str; //源字串 char *str1_temp = str1; //要求替換的字串 char *str2_temp = str2; //替換成字串 char *strretu_temp = NULL;//目標字串 unsigned long char_size = (unsigned long)sizeof(char); /*計算字元長度*/ unsigned long i,j,rep_acc = 0; unsigned long str_len = strlen(str); unsigned long str1_len = strlen(str1); unsigned long str2_len = strlen(str2); /*首先找出Str裡有幾個地方要被替換的*/ for(; str_temp - str < str_len; ) { for(i = 0; i < str1_len; i++) { if(*str_temp++ != *str1_temp++) { str1_temp = str1; break; } else { if(i == str1_len - 1) { str1_temp = str1; rep_acc++;//找到了 } } } } str1_temp = str1; str_temp = str; /*分配所需記憶體*/ strretu = strretu_temp = malloc(((str_len - str1_len * rep_acc) + str2_len * rep_acc + 1) * char_size); /*替換*/ for(; str_temp - str < str_len; ) { for(i = 0; i < str1_len; i++) { *strretu_temp++ = *str_temp; if(*str_temp++ != *str1_temp++) { str1_temp = str1; break; } else { if(i == str1_len - 1) { strretu_temp = strretu_temp - str1_len; for(i = 0; i < str2_len; i++) { *strretu_temp++ = *str2_temp++; } str2_temp = str2; str1_temp = str1; } } } } *strretu_temp = "\0"; str1_temp = str1; str_temp = str; str2_temp = str2; return(strretu);}
回覆列表
/* 功能:查詢替換函式 返回值:替換後的字串 strretu */char *Replace(char *str, char *str1, char *str2, char *strretu){ char *str_temp = str; //源字串 char *str1_temp = str1; //要求替換的字串 char *str2_temp = str2; //替換成字串 char *strretu_temp = NULL;//目標字串 unsigned long char_size = (unsigned long)sizeof(char); /*計算字元長度*/ unsigned long i,j,rep_acc = 0; unsigned long str_len = strlen(str); unsigned long str1_len = strlen(str1); unsigned long str2_len = strlen(str2); /*首先找出Str裡有幾個地方要被替換的*/ for(; str_temp - str < str_len; ) { for(i = 0; i < str1_len; i++) { if(*str_temp++ != *str1_temp++) { str1_temp = str1; break; } else { if(i == str1_len - 1) { str1_temp = str1; rep_acc++;//找到了 } } } } str1_temp = str1; str_temp = str; /*分配所需記憶體*/ strretu = strretu_temp = malloc(((str_len - str1_len * rep_acc) + str2_len * rep_acc + 1) * char_size); /*替換*/ for(; str_temp - str < str_len; ) { for(i = 0; i < str1_len; i++) { *strretu_temp++ = *str_temp; if(*str_temp++ != *str1_temp++) { str1_temp = str1; break; } else { if(i == str1_len - 1) { strretu_temp = strretu_temp - str1_len; for(i = 0; i < str2_len; i++) { *strretu_temp++ = *str2_temp++; } str2_temp = str2; str1_temp = str1; } } } } *strretu_temp = "\0"; str1_temp = str1; str_temp = str; str2_temp = str2; return(strretu);}