提交记录 #354
提交时间:2024-12-02 17:34:19
语言:c
状态:Unaccepted
编译情况:编译成功
固定测试点#1:
固定测试点#2:
固定测试点#3:
额外测试点#5:
52【字符】字符替换*——用指针更方便
#include <stdio.h>
#include <string.h>
void replace(char *a, char *b, char *c) {
int l1 = strlen(a); // 源字符串的长度
int l2 = strlen(b); // 被替换的子串长度
int l3 = strlen(c); // 替换成的子串长度
char result[101]; // 存储替换后的字符串
int resultIndex = 0; // 结果数组的当前索引
int i = 0;
while (i < l1) {
// 找到子串 b 的匹配位置
if (strncmp(&a[i], b, l2) == 0) {
// 如果匹配,复制替换串 c 到结果
for (int j = 0; j < l3; j++) {
result[resultIndex++] = c[j];
}
i += l2; // 跳过已匹配的部分
} else {
// 如果没有匹配,复制当前字符到结果
result[resultIndex++] = a[i++];
}
}
result[resultIndex] = '\0'; // 确保字符串结尾
printf("%s\n", result); // 输出替换后的字符串
}
int main() {
char a[100], b[10], c[10];
// 使用 fgets 代替 gets,防止缓冲区溢出
fgets(a, sizeof(a), stdin);
fgets(b, sizeof(b), stdin);
fgets(c, sizeof(c), stdin);
// 去除 fgets 输入的换行符
a[strcspn(a, "\n")] = '\0';
b[strcspn(b, "\n")] = '\0';
c[strcspn(c, "\n")] = '\0';
replace(a, b, c);
return 0;
}