문제

Hello I'm doing a software that search in string 1 at least a one character from a string 2 and print The location of what we found.

The problem in my program is that it prints incorrect values

My code -

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

int main()
{
    char str1[] = "a,s,e,d,8,f";
    char str2[] = "1,2,3,4,5,6,7,8,9,0";
    int i, j, len1, len2, con = 0;

    len1 = strlen(str1);
    len2 = strlen(str2);

    for (i = 0; i < len1; i++)
    {
        for (j = 0; j < len2; j++)
        {
            if (str1[i] == str2[j])
            {
                break;
            }
        }
        con++;
    }
    printf("%d", con);
    system("PAUSE");
}

The return value should be 5 because 8 appears in the second string and the position 5

Thanks to those who could understand the problem and help me solve it, I appreciate it very much

도움이 되었습니까?

해결책 2

Just add a 'continue' instruction over the ',' char and a flag 'find' when you find the correct char :

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

int main()
    {
    char str1[] = "a,s,e,d,8,f";
    char str2[] = "1,2,3,4,5,6,7,8,9,0";
    int i, j, len1, len2, find = 0, con = 0;

    len1 = strlen(str1);
    len2 = strlen(str2);

    for (i = 0; i < len1; i++)
    {

        if(str1[i]==',')
            continue;

        for (j = 0; j < len2; j++)
        {
            if (str1[i] == str2[j])
            {
                find = 1;
                break;
            }
        }

        con++;

        if(find>0)
            break;

    }
    printf("%d\n", con);

}

다른 팁

"break" only breaks the inner "j" loop, leaving the outer "i" loop to keep running. See this post for ways to fix. How to break out of nested loops?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top