提交记录 #400
提交时间:2024-12-03 16:30:25
语言:c
状态:Unaccepted
编译情况:编译成功
code.c: In function ‘replace’:
code.c:10:15: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
10 | char *k = malloc(a + 1); // 分配足够的空间以存储结果字符串
| ^~~~~~
code.c:10:15: warning: incompatible implicit declaration of built-in function ‘malloc’
code.c:4:1: note: include ‘<stdlib.h>’ or provide a declaration of ‘malloc’
3 | #include <string.h>
+++ |+#include <stdlib.h>
4 |
code.c:36:5: warning: implicit declaration of function ‘free’ [-Wimplicit-function-declaration]
36 | free(k); // 释放k分配的内存
| ^~~~
code.c:36:5: warning: incompatible implicit declaration of built-in function ‘free’
code.c:36:5: note: include ‘<stdlib.h>’ or provide a declaration of ‘free’
code.c:8:9: warning: unused variable ‘c’ [-Wunused-variable]
8 | int c = strlen(str);
| ^
固定测试点#1:
固定测试点#2:
固定测试点#3:
附加测试点暂不可用
52【字符】字符替换*——用指针更方便
#include <stdio.h>
#include <string.h>
void replace(char *s, char *t, char *str) {
int a = strlen(s);
int b = strlen(t);
int c = strlen(str);
char *p = s;
char *k = malloc(a + 1); // 分配足够的空间以存储结果字符串
if (k == NULL) {
// 处理内存分配失败的情况
return;
}
k[0] = '\0'; // 初始化k为空字符串
while (*p != '\0') {
char *q = p;
int i = 0;
while (*q != '\0' && *t != '\0' && *q == *t) {
q++;
t++;
i++;
}
if (*t == '\0' && i == b) {
strcat(k, str); // 如果找到匹配的子串t,追加str到k
p += i; // 移动p到t的末尾
t = t - i + b; // 重置t指针
} else {
strcat(k, p); // 追加不匹配的部分到k
p++; // 移动p指针
}
t = t - i; // 重置t指针
}
strcpy(s, k); // 将k的内容复制回s
free(k); // 释放k分配的内存
}
int main() {
char s[100];
char t[100]; // 增加t的大小以避免潜在的溢出
char str[100]; // 增加str的大小以避免潜在的溢出
fgets(s, sizeof(s), stdin);
int a = strlen(s);
if (a > 0 && s[a-1] == '\n') {
s[a-1] = '\0';
}
fgets(t, sizeof(t), stdin);
int b = strlen(t);
if (b > 0 && t[b-1] == '\n') {
t[b-1] = '\0';
}
fgets(str, sizeof(str), stdin);
int c = strlen(str);
if (c > 0 && str[c-1] == '\n') {
str[c-1] = '\0';
}
replace(s, t, str);
printf("%s\n", s);
return 0;
}