admin 管理员组

文章数量: 1086019


2024年4月17日发(作者:transaction是什么意思啊)

c语言replace函数用法

C语言标准库中没有replace函数,需要使用字符串操作函数

来实现字符串的替换。下面是使用字符数组和字符串操作函数

实现替换的示例代码:

```c

#include

#include

int main() {

char str[100] = "hello world, world";

char old_str[20] = "world";

char new_str[20] = "c language";

int old_len = strlen(old_str);

int new_len = strlen(new_str);

char *pos = strstr(str, old_str);

while (pos != NULL) {

memmove(pos + new_len, pos + old_len, strlen(pos + old_len)

+ 1);

memcpy(pos, new_str, new_len);

pos = strstr(pos + new_len, old_str);

}

printf("%sn", str);

return 0;

}

```

以上代码将在字符串"hello world, world"中将"world"替换成"c

language",输出结果为:"hello c language, c language"。


本文标签: 函数 字符串 使用 操作 替换