#include
#include
int replace_str(char* s, char* t, char* g) {
int i, j, k,n,count=0;
n = strlen(t);
char temp[80];
for (i = 0; s[i] != '\0'; i++) {
for (j = i, k = 0; s[j] == t[k] && t[k] != '\0'; j++, k++)
{
if (t[k+1] == '\0') {
strcpy(temp, s +i+ n);
s[i] = '\0';
strcat(s, t);
strcat(s, temp);
count++;
break;
}
}
} return count;
}
int main() {
char s[80],t[10],g[10];
gets(s);
gets(t);
gets(g);
replace_str(s, t, g);
puts(s);
printf("count=%d", replace_str(s, t, g));
return 0;
}
int replace_str(char *s, char *t, char *g)
{
int i, j, k, n, count = 0;
n = strlen(t);
char temp[80];
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] == *t) // t首字符相同开始比较
{
k = 0;
while (t[k] == s[i + k] && k < n && s[i + k] != '\0') // 比较整个t
k++;
if (k == n) // 匹配到字符串t
{
s[i] = '\0';
strcpy(temp, s + i + k); // 暂存匹配字符后面内容
strcat(s, g); // g连接到s
strcat(s, temp); // 再把s后面部分链接回来
}
i += k;//跳过替换部分中查找
count++;
}
}
return count;
}
int main()
{
char s[80], t[10], g[10];
int count;
gets(s);
gets(t);
gets(g);
count = replace_str(s, t, g);
puts(s);
printf("count=%d", count); //
return 0;
}
修改后的代码如下,望采纳,有问题随时沟通
#include<stdio.h>
#include<string.h>
// 替换字符串 s 中子串 t 的所有出现位置,用子串 g 替换
int replace_str(char* s, char* t, char* g) {
int i, j, k, count=0;
int n = strlen(t);
// 子串 t 的长度
int m = strlen(s);
// 字符串 s 的长度
// 遍历字符串 s,寻找子串 t 的出现位置
for (i = 0; i < m; i++) {
// 如果子串 t 在字符串 s 的当前位置开始
if (strncmp(s+i, t, n) == 0) {
// 用子串 g 替换子串 t
for (j = 0; j < n; j++) {
s[i+j] = g[j];
}
// 增加替换次数的计数器
count++;
}
}
// 返回进行了多少次替换
return count;
}
int main() {
char s[80], t[10], g[10];
// 从用户处读入输入字符串
gets(s);
gets(t);
gets(g);
// 用子串 g 替换字符串 s 中的子串 t
replace_str(s, t, g);
// 打印结果字符串
puts(s);
printf("count=%d", replace_str(s, t, g));
return 0;
}