将字符串中的子串替换为另一个字串 参数: str, 源字符串 old, 需替换的子串 New, 新的子串 返回: 如找到,返加子串的位置,否则返回-1 写一下C语言代码
时间: 2024-11-22 21:36:39 浏览: 81
在C语言中,你可以使用strstr()
函数来查找源字符串str
中是否包含子串old
,然后通过memmove()
或者strcpy()
结合指针操作来替换子串。如果找到了子串,可以使用strncpy()
或者strcpy()
将新的子串New
复制到相应位置。这里是一个简单的示例代码:
#include <stdio.h>
#include <string.h>
int replace_substring(char* str, const char* old, const char* new_str) {
size_t old_len = strlen(old);
size_t new_len = strlen(new_str);
// 查找子串
char* pos = strstr(str, old);
if (pos == NULL) { // 如果没找到,返回 -1
return -1;
}
// 计算新子串在原字符串中的起始位置
size_t start_pos = pos - str;
// 移除旧的子串并添加新的子串
memmove(pos + new_len, pos + old_len, strlen(pos + old_len) + 1); // 移动剩余部分
strncpy(pos, new_str, new_len); // 插入新的子串
return start_pos; // 返回新子串的位置
}
int main() {
char str[] = "Hello, world!";
char old[] = "world";
char new_str[] = "CSDN";
int position = replace_substring(str, old, new_str);
if (position != -1) {
printf("替换后的字符串:%s\n", str);
} else {
printf("未找到需要替换的子串。\n");
}
return 0;
}
这个代码会在"Hello, world!"这个例子中将"world"替换成"CSDN",并将结果打印出来。
相关推荐


















