在C语言中,字符串替换函数通常使用strcpy()
和strcat()
函数来实现。下面是一个简单的示例:
#include#include void replaceString(char *str, const char *find, const char *replace) { char result[1000]; char *p = strstr(str, find); if (!p) { printf("String not found\n"); return; } strncpy(result, str, p - str); result[p - str] = '\0'; strcat(result, replace); strcat(result, p + strlen(find)); strcpy(str, result); } int main() { char str[100] = "Hello, world!"; replaceString(str, "world", "C programming"); printf("%s\n", str); return 0; }
在上面的例子中,replaceString
函数用于将字符串str
中的find
字符串替换为replace
字符串。在main
函数中,我们首先定义一个字符串"Hello, world!"
,然后调用replaceString
函数进行替换操作,最后输出替换后的字符串。