【发布时间】:2020-09-01 15:37:06
【问题描述】:
谁能告诉我这里的错误是什么。我在这里使用了二维数组。
#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;
}
我希望输出如下所示。 例如:
enter a string: vicky is a good boy
enter the word which has to be replaced: good
enter the word with which it has to be replaced: bad
vicky is a bad boy
我的意思是我只想替换那个特定的单词,就像它出现在字符串中一样多次,比如这里,单词 good。谁能帮我找出错误或帮我找到另一种方法。
【问题讨论】:
-
使用描述性变量名,而不是
a、b、c等 -
你的程序看起来有点矫枉过正。逻辑没有那么复杂。例如,您可以使用
strstr定位"good"。
标签: c arrays string multidimensional-array