比如输入
{panda,tiger,lion,mouse}
{lion,tiger}
(注:输入时“{}” “,”也在,不能省)
输出
lion tiger
目的是输出有重复的单词,
还有请问我这个代码错误的原因是什么呢,要怎样修改呢?
#include
#include
void maxword(char *s,char *t)
{
int i,j=0,m=0;
char p[20][30]= {0};
for(i=0; s[i]!='\0'; i++)
{
if(s[i]!=' ')
p[m][j++]=s[i];
else
{ p[m][j]='\0';
m++;
j=0;
}}
for(i=0; iif(strstr(t,p[i])!=NULL) {
printf("the same word:%s\n",p[i]);
}}}
void main()
{
scanf("{");
char s[100];
scanf("%s,",s);
scanf("}");
scanf("{");
char t[100];
scanf("%s,",t);
scanf("}");
maxword(s,t);
}
代码可以调整的点:
修改后的代码:
#include<stdio.h>
#include<string.h>
void maxword(char *s,char *t) {
char p[20][30];
int i,m=0,j=0;
for (i=0; s[i]!='\0'; i++) {
if(s[i]!=' ')
p[m][j++]=s[i]; else {
p[m][j]='\0';
m++;
j=0;
}
}
for (i=0; i<m; i++) {
if(strcmp(t,p[i])==0) {
printf("the same word:%s\n",p[i]);
}
}
}
int main() {
char s[100];
scanf("%[{]",s);
scanf("%[^}]",s);
scanf("%[}]",s);
char t[100];
scanf("%[{]",t);
scanf("%[^}]",t);
scanf("%[}]",t);
maxword(s,t);
return 0;
}
#include<stdio.h>
#include<string.h>
void maxword(char *s,char *t)
{
int i,j=0,m=0;
char p[20][30]= {0};
for(i=0; s[i]!='\0'; i++)
{
if (s[i] == '{' || s[i] == '}')
continue;
if(s[i] != ',')
p[m][j++]=s[i];
else
{
p[m][j]='\0';
m++;
j=0;
}
}
for(i=0; i<m; i++) {
if(strstr(t,p[i])!=NULL) {
printf("the same word:%s\n",p[i]);
}
}
}
void main()
{
char s[100];
scanf("%s,",s);
char t[100];
scanf("%s,",t);
maxword(s,t);
}
学会了,别忘了采纳。其实方法有很多,先举两例,你可以使用以下代码来实现目的:
#include<stdio.h>
#include<string.h>
void maxword(char *s, char *t) {
int i, j = 0, m = 0;
char p[20][30] = {0};
for(i=0; s[i]!='\0'; i++) {
if(s[i]!=' ')
p[m][j++]=s[i];
else {
p[m][j]='\0';
m++;
j=0;
}
}
for(i=0; i<m; i++) {
if(strstr(t,p[i])!=NULL)
printf("the same word:%s\n",p[i]);
}
}
void main() {
char s[100];
char t[100];
scanf("{%[^}],} {%[^}],}", s, t);
maxword(s, t);
}
可以使用scanf("{%[^}],} {%[^}],}", s, t)来替换原来的scanf()函数,它会将“{panda,tiger,lion,mouse}{lion,tiger}”输入读取到s和t变量,这样就可以在maxword()函数中处理字符串了。如果你使用的是scanf("{%[^}],} {%[^}],}", s, t),那么t的值就是"lion,tiger",那么t的值就是"lion,tiger"。如果你使用的是scanf("{%[^}],} {%[^}],}", s, t),那么输出的结果是the same word: lion和the same word: tiger。
还有另外一个方式就是,运用getchar函数,进行所谓的循环操作
你可以使用以下代码进行输入:
int getCharIndex = 0;
char s[30], t[30];
while (1) {
char c = getchar( );
if (c == '{') {
int i = 0;
while (1) {
c = getchar( );
if (c == '}')
break;
s[i] = c;
i++;
}
s[i] = '\0';
} else if (c == '{') {
int i = 0;
while (1) {
c = getchar( );
if (c == '}')
break;
t[i] = c;
i++;
}
t[i] = '\0';
}
if (getCharIndex >= 30 || c == EOF || c == '\n')
break;
getCharIndex++;
}
嗯,我暂时就这两种方式😇,兄弟,点个关注。以后有其他问题可以随时问我。