c替换字符串中的单词怎么编程

时间:2025-01-29 01:59:19 网络游戏

在C语言中,替换字符串中的单词可以通过以下几种方法实现:

方法一:使用 `strstr` 和 `strcat`

```c

include

include

int main() {

char str;

char strtemp;

char str3;

puts("请输入初始字符串:");

gets(str);

puts("请输入要被替换掉的字符串:");

gets(strtemp);

puts("请输入要去替换的字符串:");

gets(str3);

if(strstr(str, strtemp) == NULL) {

printf("没有字符串%s\n", strtemp);

return 1;

}

char *str1 = (char*)malloc(strlen(strstr(str, strtemp)) + 1);

strcpy(str1, strstr(str, strtemp));

str2 = strstr(str, strtemp);

*str2 = '\0';

strcat(str, str3);

strcat(str, str1 + strlen(strtemp));

puts(str);

free(str1);

return 0;

}

```

方法二:使用 `replace` 函数

```c

include

include

void replace(char* org, char* find, char* rep) {

char *p1, *p2;

while ((p1 = strstr(org, find)) != NULL) {

p2 = p1 + strlen(find);

memmove(p1 + strlen(rep), p2, strlen(p2) + 1);

memcpy(p1, rep, strlen(rep) + 1);

}

}

int main() {

char a = "猫和老鼠";

replace(a, "猫", "Tom");

replace(a, "老鼠", "Jerry");

puts(a);

return 0;

}

```

方法三:使用自定义函数

```c

include

include

include

char *str_replace(const char *str, const char *old, const char *new) {

char *result;

int i, count = 0;

int newlen = strlen(new);

int oldlen = strlen(old);

for (i = 0; str[i] != '\0'; i++) {

if (strncmp(&str[i], old, oldlen) == 0) {

count++;

i += oldlen - 1;

}

}

result = (char *)malloc(i + count * (newlen - oldlen) + 1);

if (result == NULL) {

printf("Memory allocation failed.\n");

exit(1);

}

i = 0;

while (*str) {

if (strncmp(str, old, oldlen) == 0) {

strcpy(&result[i], new);

i += newlen;

str += oldlen;

} else {

result[i++] = *str;

}

}

result[i] = '\0';

return result;

}

int main() {

const char *str = "I love C";

const char *old = "C";

const char *new = "Python";

char *result = str_replace(str, old, new);

printf("%s\n", result);

free(result);

return 0;

}

```

方法四:使用标准库中的 `string.h`

```c

include

include

int main() {

char s[] = "I love C";

char *pos = strstr(s, "C");

if (pos != NULL) {

*pos = 'P';

}

printf("%s\n", s);

return 0;

}

```

这些方法都可以实现字符串中单词的替换。选择哪种方法取决于具体的需求和场景。