提交记录 #435
提交时间:2024-12-03 23:03:52
语言:c
状态:Unaccepted
编译情况:编译成功
固定测试点#1:
固定测试点#2:
固定测试点#3:
额外测试点#10:
52【字符】字符替换*——用指针更方便
#include <stdio.h>
#include <string.h>
void replaceString(char *s, const char *t, const char *str) {
char result[110]; // 存储替换后的字符串,长度至少为110
int s_len = strlen(s);
int t_len = strlen(t);
int str_len = strlen(str);
int result_index = 0;
for (int i = 0; i < s_len; ) {
// 检查当前位置是否是被替换串的开头
if (strncmp(&s[i], t, t_len) == 0) {
// 如果是,将替换串复制到结果字符串中
strcpy(&result[result_index], str);
result_index += str_len;
i += t_len; // 跳过被替换串
} else {
// 如果不是,将源串中的字符复制到结果字符串中
result[result_index++] = s[i++];
}
}
result[result_index] = '\0'; // 添加字符串结束符
strcpy(s, result); // 将结果字符串复制回源串
}
int main() {
char s[110]; // 源串,长度至少为110
char t[12]; // 被替换串,长度至少为12
char str[12]; // 替换串,长度至少为12
// 输入源串、被替换串和替换串
fgets(s, sizeof(s), stdin);
fgets(t, sizeof(t), stdin);
fgets(str, sizeof(str), stdin);
// 去除换行符
s[strcspn(s, "\n")] = '\0';
t[strcspn(t, "\n")] = '\0';
str[strcspn(str, "\n")] = '\0';
// 替换字符串
replaceString(s, t, str);
// 输出替换后的字符串
printf("%s\n", s);
return 0;
}