Sprawdzanie podciągu w tablicy

0

Sprawdzanie podciągu 'what' w tablicy 'where'

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

int amount_substring(const char* where, const char* what)
{
    int i, amount = 0;
    int is;
    while (where != '\0')
        is = 1;
        for (i = 0; i < strlen(what); ++i) {
            *where++ == what[i] ? is = 1 : is = 0; // co jest nie tak z tą instrukcją
            if (is == 0)
                break;
        }

    return amount;
}

int main()
{
    char substring[] = { "tak" };
    char Fullstr[] = "tak,tak,nie";
    amount_substring(Fullstr, substring);
    return 0;
}


0

Pomijając to czy w ogóle instrukcja robi dokładnie to chcesz zamierzasz, to syntaktycznie powinno być

is = (*where++ == what[i]) ? 1 : 0;
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int amount_substring(const char* where, const char* what)
{
    int i, amount = 0;
    int is;
    while (*where != '\0'){
        is = 1;
        for (i = 0; i < strlen(what); ++i) {
            is = (*where++ == what[i]) ? 1 : 0;
            if (is == 0)
                break;
            if(i == strlen(what)) ++amount;
        }
    }
    return amount;
}

int main()
{
    char substring[] = { "tak" };
    char Fullstr[] = "tak,tak,nie";
    printf("%d",amount_substring(Fullstr, substring));
    return 0;
}

0

Ten kod się wysypie jeśli where jest krótsze od what i mają takie same znaki (inaczej mówiąc, where jest prefiksem what).

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

int amount_substring(const char* where, const char* what)
{
    int i, amount = 0;
    int is;
    if(strlen(where) < strlen(what)) return 0;
    while (*where){
        is = 1;
        for (i = 0; i < strlen(what); ++i) {
            is = (*where++ == *(what+i)) ? 1 : 0;
            if (is == 0)
                break;
            if(i == strlen(what - 1)) ++amount;
        }
    }
    return amount;
}

int main()
{
    char substring[] = { "tak" };
    char Fullstr[] = "ta";
    printf("%d",amount_substring(Fullstr, substring));
    return 0;
}

no cóż, ;-; zrobiłem tak

0

co to ma niby robić? *where++ == what[i] ? is = 1 : is = 0; // co jest nie tak z tą instrukcją?
where wskazuje na const char.

Na dodatek po co sobie utrudniać życie?

int amount_substring(const char* where, const char* what)
{
    int result = 0;
    assert(where);
    assert(what);

    while (where && *where) {
          where = strstr(where, what);
          if (where) {
               ++where;
               ++result;
          }
    }
    return result;
}

Zakładam, że amount_substring("aaaa", "aa") ma zwrócić 3.

1 użytkowników online, w tym zalogowanych: 0, gości: 1