C 将字符串中的一个单词替换为另一个单词
谁能告诉我这里出了什么错吗。我在这里使用了二维数组C 将字符串中的一个单词替换为另一个单词,c,arrays,string,multidimensional-array,C,Arrays,String,Multidimensional Array,谁能告诉我这里出了什么错吗。我在这里使用了二维数组 #include<stdio.h> #include<string.h> int main() { char a[100], b[30][30], c[20], d[20]; int i, j=0, k, count=0; int e[30]; printf("enter a string: "); gets(
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[30][30], c[20], d[20];
int i, j=0, k, count=0;
int e[30];
printf("enter a string: ");
gets(a);
printf("enter the word which has to be replaced: ");
gets(c);
printf("enter the word with which it has to be replaced: ");
gets(d);
for(i=0,k=0, e[i]=0; i<strlen(a); i++, k++)
{
if(a[i]==' ')
{
k=0;
j++;
count++;
}
else
{
b[j][k]=a[i];
e[i]++;
}
}
for(i=0; i<j; i++)
{
if(word(b[i], c)==0)
{
for(k=0; k<strlen(d); k++)
{
b[i][k]=d[k];
}
}
}
for(i=0; i<count; i++)
{
for(j=0; j<e[i]; j++)
{
printf("%c", b[i][j]);
}
printf(" ");
}
}
int word(char *a, char *c)
{
int i;
if(strlen(a)==strlen(c))
{
for(i=0; i<strlen(a); i++)
{
if(a[i]!=c[i])
{
return 1;
}
}
}
else
return 2;
return 0;
}
我的意思是我只想替换那个特定的单词,就像它在字符串中出现的次数一样,比如这里,单词good。谁能帮我找出错误或帮我找到另一种方法。你不应该使用gets,它很危险:
您应该使用fgets来读取stdin
在word函数中,使用strlen函数比较两个字符串的长度:
if(strlen(a)==strlen(c))
但在main函数中,您将其称为:
if(word(b[i], c)==0)
b[i]是字符数组,但不能在每个单词的末尾添加空字符\0。所以斯特伦不会像你想的那样工作
在用d替换字符串c的代码中。您不能更新e数组的值。
我认为,e[I]应该是:
e[i] = strlen(d);
我似乎没有为字符串使用一些标准函数,例如,对您的程序非常有用
strcmp比较字符串和字符串
strstr在字符串中查找单词
如果你在谷歌搜索,你可以有大量的代码为你的案件
例如:
另一个:使用描述性变量名,而不是a、b、c等。您的程序看起来有些过头了。逻辑并没有那么复杂。例如,您可以使用strstr查找好的。
e[i] = strlen(d);