1

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

ajay
  • 9,402
  • 8
  • 44
  • 71
user3332897
  • 23
  • 2
  • 8

2 Answers2

3

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

Community
  • 1
  • 1
La-comadreja
  • 5,627
  • 11
  • 36
  • 64
  • You can be more precise and give me the "concept" of breaking I need? – user3332897 Mar 04 '14 at 18:12
  • Also, you need to make sure the commas are counted the right way. They do increase the length if they're extra characters. You may just want to delete them when you are declaring the arrays. – La-comadreja Mar 04 '14 at 18:15
1

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

}
brobertie
  • 120
  • 6