C語言中字符串替換的方法有以下幾種:
char *str_replace(char *str, char from, char to) {
char *p = strchr(str, from);
if (p != NULL) {
*p = to;
}
return str;
}
char *str_replace(char *str, char *from, char *to) {
char *new_str = (char *)malloc(strlen(str) + strlen(to) - strlen(from) + 1);
char *p = strstr(str, from);
if (p != NULL) {
strncpy(new_str, str, p - str);
new_str[p - str] = '\0';
strcat(new_str, to);
strcat(new_str, p + strlen(from));
} else {
strcpy(new_str, str);
}
return new_str;
}
void str_replace(char *str, char *from, char *to) {
char buffer[MAX_BUFFER_SIZE];
sprintf(buffer, "%s", str);
sscanf(buffer, from, to);
strcpy(str, buffer);
}
char *str_replace(char *str, char *from, char *to) {
char *token;
char *new_str = (char *)malloc(strlen(str) + strlen(to) + 1);
strcpy(new_str, "");
token = strtok(str, from);
while (token != NULL) {
strcat(new_str, token);
strcat(new_str, to);
token = strtok(NULL, from);
}
return new_str;
}
注意:以上方法都需要保證目標字符串足夠大,以防止溢出。另外,需要注意字符串的結束符’\0’的處理。