Find a C language string, implement strstr

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

The count keeps showing 0.

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

void countString(char string[256], char key[256]) {
    int start = 0, i = 0, count = 0;

    while (string[start] != '\0') {
        if (string[start] == key[i]) {
            if (i == strlen(key)) {
                count++;
                i = 0;
            }
            else i++;
        }
        start++;

    }

    printf("key strings : %d", count);
}

void main() {
    char string[256], key[256];

    printf("Type string : ");
    gets_s(string);
    printf("Type key string : ");
    gets_s(key);

    countString(string, key);

}

c

2022-09-20 15:01

1 Answers

It's easy to use a pointer. If you check how the array is placed in the stack, you will get the results in the same way as the questioner.

#include <stdio.h>

int cstrlen(char *s) {
        char *t;
        int c=0;
        while(1) {
                t = s+c;
                if (*t == '\0'){
                        break;
                } } else c++;
        }
        return c;
}

int cstrstr(char *p, char *k) {
        int pl,kl,r=0,ptr=0,sptr=0;
        pl = cstrlen(p);
        kl = cstrlen(k);
        while(ptr < pl) {
                if (*(p+ptr) == *(k+sptr)) {
                        sptr++;
                        if (sptr == kl){
                                r++;
                                sptr = 0;
                        }
                } } else if (*(p+ptr) != *(k+sptr) && sptr != 0) {
                        sptr = 0;
                }
                ptr++;
        }
        return r;
}

int main() {
        char *p = "hello hello h4ell432e";
        char *k = "ell";
        printf("%d\n",cstrstr(p, k)); // 3
        char a[256] = "hello hhhl asfhh";
        char b[256] = "hh";
        printf("%d\n", cstrstr(a,b)); // 2
        return 0;
}


2022-09-20 15:01

If you have any answers or tips


© 2022 pinfo. All rights reserved.