我对C非常陌生,我决定创建一个名为str_replace的函数,它替换使用malloc创建的字符串内部的字符串。它似乎工作,但任何人都可以找到任何改善的余地。有什么办法来改善这个函数,用malloc分配的字符串中的另一个字符串替换子字符串的出现?
任何意见将不胜感激。我想知道,如果人们认为找到出现次数来计算新的字符串大小是一个好主意,并且如果我使用指针是有道理的。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char * str_replace(char * string,char * find,char * replace){
//Replaces each occurence of a particular string inside a malloc-made string with another string
char * pos = string;
size_t replace_size = strlen(replace);
size_t find_size = strlen(find);
size_t excess = replace_size - find_size;
//Get number of occurences
int x = 0;
while (1) {
pos = strstr(pos,find);
if (pos == NULL){
break;
}
pos++;
x++;
}
if (!x){ //No occurences so return with original string
return string;
}
char * new_string = malloc(sizeof(char)*(strlen(string) + excess*x + 1)); //Plus 1 for null termination
pos = string; //Reset pointer
char * string_track = string; //Used to move around string.
char * new_string_begin = new_string; //Begining of new string to return
while (1) {
pos = strstr(pos,find);
if (pos == NULL){
strcpy(new_string,string_track); //Fill in remainder
break;
}
pos++;
size_t seg_len = pos-string_track; //Length between found string and last
strncpy(new_string,string_track,seg_len); //Copy string to just before pos
new_string += seg_len - 1; //Go to point for replacement by adding what was added to pointer.
strncpy(new_string,replace,replace_size);
new_string += replace_size; //Go to point after what was replaced
string_track = pos + find_size - 1; //Original string should go to point after found string.
}
free(string); //Remove old string
return new_string_begin; //return new string
}
int main (int argc, const char * argv[]) {
char * string = malloc(sizeof(char)*21);
strcpy(string,"No,yes,no,yes,no,yes");
printf("%s\n",string);
string = strreplace(string, "no", "nope");
printf("%s\n",string);
free(string);
string = malloc(sizeof(char)*21);
strcpy(string,"No,yes,no,yes,no,yes");
printf("%s\n",string);
string = strreplace(string, "hello", "nope");
printf("%s\n",string);
free(string);
string = malloc(sizeof(char)*21);
strcpy(string,"No,yes,no,yes,no,yes");
printf("%s\n",string);
string = strreplace(string, "yes", "y");
printf("%s\n",string);
free(string);
return 0;
}
尝试存储针的位置,因此您不必搜索两次。 – arthurprs 2012-04-23 00:04:33