提交记录 #405
提交时间:2024-12-03 16:41:25
语言:c
状态:Unaccepted
编译情况:编译成功
固定测试点#1:
固定测试点#2:
固定测试点#3:
额外测试点#5:
52【字符】字符替换*——用指针更方便
#include <stdio.h>
#include <string.h>
#include <stdlib.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
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0'; // 去除换行符
// 读取被替换串 t
fgets(t, sizeof(t), stdin);
t[strcspn(t, "\n")] = '\0'; // 去除换行符
// 读取替换串 str
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // 去除换行符
// 执行替换
char* result = replaceSubstring(s, t, str);
if (result) {
printf("%s\n", result); // 输出替换后的字符串
free(result); // 释放动态分配的内存
} else {
printf("替换过程中发生错误。\n");
}
return 0;
}
// 字符串替换函数
char* replaceSubstring(char* source, const char* toReplace, const char* replacement) {
char *pos, *dst, *end;
size_t toReplaceLen = strlen(toReplace);
size_t replacementLen = strlen(replacement);
size_t sourceLen = strlen(source);
size_t resultLen = sourceLen; // 初始结果长度等于源长度
// 计算结果字符串的最终长度
for (pos = source; (pos = strstr(pos, toReplace)) != NULL; pos += toReplaceLen) {
resultLen += replacementLen - toReplaceLen;
}
// 分配内存
dst = (char*)malloc(resultLen + 1);
if (!dst) return NULL;
end = dst; // end 指向当前写入位置
// 复制字符串,执行替换
while ((pos = strstr(source, toReplace)) != NULL) {
size_t offset = pos - source;
memcpy(end, source, offset);
end += offset;
memcpy(end, replacement, replacementLen);
end += replacementLen;
source += offset + toReplaceLen;
}
strcpy(end, source); // 复制剩余的字符串
return dst;
}