Question

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

Was it helpful?

Solution 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);

}

OTHER TIPS

"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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top