c for loop break statement doesn't work

424 views Asked by At

I've written a for loop that searches a string in another. I want it to rename it's position when it finds it. ( I am open for new suggestions for the search :) )

int search (char str1[56], char str2[5]){
    int c1, c2, c3, c4;
    c1 = 0;

    for (c1=0; c1<56; c1++)
    {
        c2 = 0, c3 = 0;
        for (c2 = 0; c2 < 5; c2++){
            if (str1[c1] == str2[c2]){
                c3++;
            }
        }

        if (c3 == 5){
            c4 = c1; 
            break;
        }
    }

    return c4;
}
4

There are 4 answers

3
BLUEPIXY On BEST ANSWER
#include <stdio.h>
#include <string.h>

int search(const char str1[56], const char str2[5]){
    int c1, c2;
    int len1 = strlen(str1);
    int len2 = strlen(str2);

    for (c1=0; c1<len1-len2+1; ++c1){
        for (c2 = 0; c2 < len2; ++c2)
            if (str1[c1+c2] != str2[c2])
                break;
        if (c2 == len2)
            return c1;
    }

    return -1;//not found
}
int main(void){//DEMO
    const char *test_data[] = { "test", "the", "pro", "gram", "hte" };
    int i, size = sizeof(test_data)/sizeof(*test_data);
    for(i=0;i<size;++i){
        int result;
        result=search("test the program!", test_data[i]);
        printf("%d\n", result);//0, 5, 9, 12, -1
    }
    return 0;
}
4
Jite On

It sounds like you want strstr(), it searches for a substring in a string and returns a pointer to it if found. Strings aren't the best thing to start with when learning C, you really want to use proper libraries for that at first.

6
pepo On

in the innermost for loop you iterate over all characters of str2, but compare each of them to the same position in str1

for (c2=0; c2<5; c2++) {
    if (str1[c1] == str2[c2]) {
        c3++;
    }
}

what you want is to iterate over the characters of str1 too, i.e.

for (c2=0; c2<5; c2++) {
    if (str1[c1+c2] == str2[c2]) {
        c3++;
    }
}

this will run out of bounds on str1, you can fix this by searching only up to position length(str1) - length(str2) + 1

for (c1=0; c1<56-4; c1++) {

you should however consider not using hardcoded string lengths

0
Sourav Ghosh On

As @Jite suggested, you can go for strstr(), that's the best option. If you want add another flavor to your search, regarding comparing two strings while iGnOrInG the case, you can give a try to strcasestr().

While using either of them, don't forget to include string.h

Check out the man page of strstr() for more information. Also, for sample usage check this.