我需要找到2个字符串中的重复字符

时间:2019-01-29 04:34:46

标签: c

我正在尝试在2个字符串中找到重复的元素。这是我所做的。

int main()
{
    int i, j;
    char S[5];
    char J[4];
    printf("Enter the 1st string\n");
    scanf("%s", &S);
    printf("\nEnter the 2nd string\n");
    scanf("%s",&J);
    printf("\n1st string characters are %s", &S);
    printf("\n2nd string characters are %s", &J);


    for(i=0; i<5; i++)
    {
        for (j=0; j<3; j++)
        {

        if(J[j] == S[i])
        {
            printf("\n\nThe element is found and is at %c", *(&S[i]));
            break;
        }
        else
        {
            printf("\nNo matching element found");
            break;
        }
        }
    }
    return 0;

} 

即时通讯输出为

输入第一个字符串 asdf

输入第二个字符串 cfv

第一个字符串字符为asdf 第二个字符串字符是cfv

The element is found and is at
No matching element found
No matching element found
No matching element found
No matching element found
No matching element found

知道为什么会这样吗?我是这个菜鸟。感谢您的帮助

1 个答案:

答案 0 :(得分:3)

我可以在您的循环中提出一些建议,类似地i<strlen(S)将i <5和j <3替换为j<strlen(J) strlen用于计算字符串长度。 并且不要使用break;否则,它将在第一次比赛时跳过循环。所以试试这个

#include<stdio.h>
#include <string.h>

int main() {
 int i, j;
char S[]="rat";
char J[]="fat";


printf("\n1st string characters are %s", &S);
printf("\n2nd string characters are %s", &J);


for(i=0; S[i] != '\0';; i++)
{
    for (j=0; J[j] != '\0';; j++)
    {

    if(J[j] == S[i])
    {
        printf("\n\nThe element is found and is at %c", *(&S[i]));

    }
    else
    {
        printf("\nNo matching element found");

    }
    }
}
return 0;
}

click here to see the output输出显示在图像中。 抱歉,我的系统中没有C编译器,因此在网上使用过它,这可能就是为什么未显示位置的原因,但是可以解决检测到匹配项的问题。