/** * Brute force string search * Noting really special going on here * **/ #include #include #include #ifndef NULL #define NULL (void *)0 #endif /** * A struct to keeps together search results * Not really much of an arraylist * **/ typedef struct { int count; int array[100]; } arrayList; /** * Print the found locations * @param al -- an array list instance * **/ void printList(arrayList* al) { for (int i = 0; i < al->count; i++) printf("%d\n", al->array[i]); } /** * Return true if needle and stackpart are the same * @param needle -- a string * @param stackpart -- the other stirng * @return true iff needle and stackpart are the same * **/ int compare(char *needle, char *stackpart) { while (*needle && *stackpart) { if (*needle != *stackpart) { return 0; } needle++; stackpart++; } return (*needle == '\0'); } /** * My implementation of the library strstr function * @param needle -- a string * @param stackpart -- the other stirng * @return true iff needle and stackpart are the same * **/ int strstrGT(char* needle, char* haystack) { int hayloc = 0; //printf("%s %s\n", needle, haystack); while (*haystack != '\0') { if ((*needle == *haystack) && compare(needle, haystack)) { //printf(" %d\n", hayloc); return hayloc; } haystack++; hayloc++; } //printf("NF\n"); return -1; } /** * Find every instance of needle within haystack * @param needle -- a string * @param stackpart -- the other stirng * @return arrayList instance containing location of all matches * **/ arrayList allLocsF(char* needle, char* haystack) { arrayList ret = (arrayList){.count = 0}; int oloc = 0; int nloc; while (0 <= (nloc = strstrGT(needle, haystack + oloc))) { ret.array[ret.count++] = nloc+oloc; oloc = oloc + nloc + 1; } return ret; } /** * Make a string of the given length * @param len -- the length of the string to be created * @return a pointer to a block of memory of the given size which was malloc'd * **/ char* makeString(long len) { char *aa = malloc((len + 1) * sizeof(char)); for (int i = 0; i < len; i++) aa[i] = 'a' + (rand() % 26); aa[len] = '\0'; return aa; } int main(int argc, char const *argv[]) { srand(time(NULL)); char *haystack = makeString(atol(argv[2])); int cou = atoi(argv[3]); for (int i = 0; i < cou; i++) { char *needle = makeString(atol(argv[1])); arrayList allLocs = allLocsF(needle, haystack); printList(&allLocs); free(needle); } free(haystack); return 0; }