提交记录 #402
提交时间:2024-12-03 16:37:00
语言:c
状态:Unaccepted
编译情况:编译成功
code.c: In function ‘main’:
code.c:27:9: warning: implicit declaration of function ‘free’ [-Wimplicit-function-declaration]
27 | free(result); // 释放动态分配的内存
| ^~~~
code.c:27:9: warning: incompatible implicit declaration of built-in function ‘free’
code.c:4:1: note: include ‘<stdlib.h>’ or provide a declaration of ‘free’
3 | #include <string.h>
+++ |+#include <stdlib.h>
4 |
code.c: In function ‘replaceSubstring’:
code.c:37:23: warning: implicit declaration of function ‘strdup’; did you mean ‘strcmp’? [-Wimplicit-function-declaration]
37 | char *pos, *dst = strdup(source); // 复制源字符串以进行修改
| ^~~~~~
| strcmp
code.c:37: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);
if (result != NULL) {
printf("%s\n", result); // 输出替换后的字符串
free(result); // 释放动态分配的内存
} else {
printf("替换过程中发生错误。\n");
}
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;
}