2-5函数any

#include 
#include 

#define MAXLEN 100

char *getPart(char s[], int start, int end);
int find_word(char s[], char c[]);
void getline(char s[]);

int main(int argc, char **argv) {
    char str[MAXLEN];
    char target[MAXLEN];

    printf("Please enter the string\n");
    getline(str);
    printf("Please enter the target\n");
    getline(target);

    int target_len = strlen(target);
    
    for (int i = 0; i < target_len; ++i) {
        for (int j = i; j < target_len; ++j) {
            char *part = getPart(target, i, j);
            int index = 0;
            if (index = find_word(str, part)) {
                printf("Find a word: %s, position: %d\n", part, ++index);
            }
            free(part);
        }
    }

    return 0;
}

char *getPart(char s[], int start, int end) {
    int len = end - start;
    char *p = malloc(sizeof(char[len]));
    char *q = p;
    for (int i = start; i < end; ++i) {
        *q++ = s[i];
    }
    return p;
}

int find_word(char s[], char c[]) {
    char *p = s;

    while (*p != '\0') {
        if (*p == *c) {
            char *m = p;
            char *n = c;
            while (*m == *n) {
                ++m;
                ++n;
            }
            if (*n == '\0') {
                return p - s;
            }
        }
        ++p;
    }

    return 0;
}

void getline(char s[]) {
    char c;
    while ((c = getchar()) != EOF) {
        *s++ = c;
    }
    *s = '\0';

    return;
}

你可能感兴趣的:(C程序设计语言)