Cho hai xâu ký tự S1 và S2. Hãy viết chương trình tìm các từ chung của hai xâu S1 và S2. Chú ý: mỗi từ chỉ liệt kê 1 lần kèm theo tổng số lần xuất hiện trong 2 xâu, theo thứ tự xuất hiện trong xâu S1.
INPUT:
2
abc ab ab ab abcd ab
abc ab
aaa xyz ab zzz abc dd dd abc
dd xyz ttt sas cdc
OUTPUT:
abc 2
ab 5
xyz 2
dd 3
CODE:
#include<stdio.h>
#include<string.h>
FILE *f1 = fopen("m.inp","r");
FILE *f2 = fopen("m.out","w");
struct tu
{
char nd[100];
int xh;
};
tu ds1[100],ds2[100];
int n1=0,n2=0;
void tachtu(char s[],tu ds[],int &n)
{
char *q=strtok(s," ");
while(q!=NULL)
{
strcpy(ds[n].nd,q);
ds[n].xh=1;
n++;
q=strtok(NULL," ");
}
}
void loaitu()
{
int i,j,b[100]={0},c[100]={0};
for(i=0;i<n1;i++)
{
for(j=0;j<n2;j++)
{
if(strcmp(ds1[i].nd,ds2[j].nd)==0)
{
ds1[i].xh++;
ds2[j].xh++;
}
}
}
for(i=0;i<n1;i++)
{
if(b[i]==0)
{
b[i]=1;
for(j=i+1;j<n1;j++)
if(ds1[i].xh>1 && strcmp(ds1[i].nd,ds1[j].nd)==0)
{
b[i]++;
b[j]=-1;
}
if(ds1[i].xh>1) fprintf(f2,"%s %d\n",ds1[i].nd,ds1[i].xh);
}
}
}
main()
{
int t;
fscanf(f1,"%d\n",&t);
while(t--)
{
char s1[100],s2[100];
fgets(s1,10000,f1);
if(s1[strlen(s1)-1]=='\n') s1[strlen(s1)-1]='\0';
fgets(s2,10000,f1);
if(s2[strlen(s2)-1]=='\n') s2[strlen(s2)-1]='\0';
n1=n2=0;
tachtu(s1,ds1,n1);
tachtu(s2,ds2,n2);
loaitu();
fprintf(f2,"\n");
}
}
Phần đếm số xuất hiện các từ chung của e bị sai. Ai xem giúp vs ạ. E cám ơn.

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?