这个我记得是有更优解的,不过还是明天发吧,明天想一想,看看能不能想起来
#include<string.h>
int main()
{
char a[201] = { 0 };
char b[201] = { 0 };
scanf("%s %s", a, b);
int na = strlen(a);
int nb = strlen(b);
int i = 0, j = 0;
if (na >= nb)
{
for(i=0;i<na;i++)
{
int flag = 1;
for (j = 0; j < nb; j++)
{
if (a[i+j] != b[j])
{
flag = 0; break;
}
}
if (flag)
{
printf("%s is substring of %s\n", b, a);
return 0;
}
}
}
else
{
for (i = 0; i < nb; i++)
{
int flag = 1;
for (j = 0; j < na; j++)
{
if (b[i + j] != a[j])
{
flag = 0; break;
}
}
if (flag)
{
printf("%s is substring of %s\n", a, b);
return 0;
}
}
}
printf("No substring\n");
return 0;
}
这串代码我自己测是没问题的,可是检测过不去。
#include<string.h>
#include<ctype.h>
int main()
{
char ch[101] = { 0 };
gets(ch);
char x[100] = { 0 };
gets(x);
char y[100] = { 0 };
gets(y);
int nx = strlen(x);
int ny = strlen(y);
int n = strlen(ch);
ch[n] = 32;
int i = 0, j = 0, m = 0;
char a[100][100] = { 0 };
//分单词
for (i = 0; i < n; i++)
{
int nm = 0;
while (!isspace(ch[i]))
{
a[m][nm++] = ch[i++];
}
m++;
}
//查看是否一样,且替换
for (i = 0; i < m; i++)
{
//查看是否为待替换单词
for (j = 0; j < nx; j++)
{
if (a[i][j] != x[j])
break;
}
//如果是,替换
if (j == nx)
{
for (j = 0; j < ny; j++)
{
a[i][j] = y[j];
}
a[i][j] = 0;
//这个在替换后单词后面那个元素赋值0,防止原单词长,到时候打印出没有替换的那一部分
}
printf("%s ", &a[i][0]);
}
}
找到了
,不过不具体说了,可以自己对比一下
#include<string.h>
#include<ctype.h>
int main()
{
char ch[102] = { 0 };
gets(ch);
char x[100] = { 0 };
char y[100] = { 0 };
scanf("%s %s",x, y);
int nx = strlen(x);
int ny = strlen(y);
int n = strlen(ch);
ch[n] = 32;
int i = 0, j = 0, m = 0;
char a[101][101] = { 0 };
//分单词
for (i = 0; i < n; i++)
{
j = 0;
while (!isspace(ch[i]))
{
a[m][j++] = ch[i++];
}
m++;
}
//查看是否一样,且替换
for (i = 0; i < m; i++)
{
//查看是否为待替换单词
for (j = 0; j < nx; j++)
{
//这里要是,nx==1,且a和x的第一个一样,后面x没有了,但下面替换条件还是满足的
if (a[i][j] != x[j])
break;
}
//如果是,替换
if (a[i][j]==0&&j==nx)//所以这里加了个看看a[i][j]有没有到最后
{
for (j = 0; j < ny; j++)
{
a[i][j] = y[j];
}
a[i][j] = 0;
//这个在替换后单词后面那个元素赋值0,防止原单词长,到时候打印出没有替换的那一部分
}
printf("%s ", &a[i][0]);
}
}