提交记录 #403
提交时间:2024-12-03 16:38:09
语言:c
状态:Unaccepted
编译情况:编译成功
code.c: In function ‘replaceSubstring’:
code.c:31:23: warning: implicit declaration of function ‘strdup’; did you mean ‘strcmp’? [-Wimplicit-function-declaration]
31 | char *pos, *dst = strdup(source); // 复制源字符串以进行修改
| ^~~~~~
| strcmp
code.c:31:23: warning: initialization of ‘char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
固定测试点#1:
固定测试点#2:
固定测试点#3:
附加测试点暂不可用
52【字符】字符替换*——用指针更方便
#include <stdio.h>
#include <string.h>
// 函数声明
char* replaceSubstring(char* source, const char* toReplace, const char* replacement);
int main() {
char s[101]; // 源串 s,长度<=100
char t[11]; // 被替换串 t,长度<=10
char str[11]; // 替换串 str,长度<=10
// 读取源串 s
scanf("%100s", s); // 读取字符串,限制长度为100
// 读取被替换串 t
scanf("%10s", t); // 读取字符串,限制长度为10
// 读取替换串 str
scanf("%10s", str); // 读取字符串,限制长度为10
// 执行替换
char* result = replaceSubstring(s, t, str);
printf("%s\n", result); // 输出替换后的字符串 // 释放动态分配的内存
return 0;
}
// 字符串替换函数
char* replaceSubstring(char* source, const char* toReplace, const char* replacement) {
char *pos, *dst = strdup(source); // 复制源字符串以进行修改
if (!dst) return NULL;
while ((pos = strstr(dst, toReplace)) != NULL) {
// 替换字符串
memmove(pos + strlen(replacement), pos + strlen(toReplace), strlen(pos + strlen(toReplace)) + 1);
memcpy(pos, replacement, strlen(replacement));
}
return dst;
}