I haven't been able to test the logic inside the function yet (which I know isn't complete yet) as my program just hangs when it try to call substrings().
I have lots of messages printing to try and debug. I am only just starting to learn C so apologise for my inelegant code.
Any help to get me past this hurdle would be very much appreciated. Thank you in advance.
Code:
#include <stdio.h>
#include <ctype.h>
#define TRUE 1
#define NUM_OPTION_STATS 5
#define MAX_SUB_STRING_INPUT 20
int substrings( int *optionStats, char *source, char *subString);
int main(void){
int optionStats[NUM_OPTION_STATS];
int i=0, j=0;
char source[MAX_SUB_STRING_INPUT] = {0};
char subString[MAX_SUB_STRING_INPUT] = {0};
char in;
int finished1 = 0;
int finished2 = 0;
printf("Substrings\n");
printf("-----------\n");
do {
printf("Enter a string (1-20 characters): ");
while ((in = getchar())!= '\n') {
source[i++] = in;
}
source[i] = '\0';
if (i=0)
{
fputs("You haven't entered anything. Please try again. \n", stderr);
}
else {
finished1=1;
}
} while (finished1==0);
printf("should have worked\n");
printf("check source: %s\n", source);
i=0;
while (source[i] != '\0') {
putchar(source[i++]);
}
printf("\nMove onto substring\n");
do {
printf("Enter a substring (1-20 characters): ");
for (j=0; (in = getchar()) != '\n'; ++j) {
printf("%c\n", in);
subString[j] = in;
printf("%c\n", subString[j]);
}
subString[j] = '\0';
if (j=0)
{
fputs("You haven't entered anything. Please try again. \n", stderr);
}
if (j<=MAX_SUB_STRING_INPUT) {
finished2=1;
}
} while (finished2==0);
printf("should have worked\n");
printf("check substring: %s\n", subString);
printf("check substring 1st character: %c\n", subString[0]);
printf("About to call function\n");
printf("Let's check source again first: %s\n", source);
substrings(optionStats, source, subString); //this is where it hangs
printf("Function called\n");
}
/****************************************************************************
* Function substrings() is an implementation of the strstr() standard library
* function.
****************************************************************************/
int substrings(int *optionStats, char* source, char* subString)
{
printf("You made it into the substring function!");
int i, j, k;
int source_length, substring_length;
/*determine length of source string*/
for (i=0; i<MAX_SUB_STRING_INPUT; i++) {
while (source[i] != '\0') {
source_length++;
}
}
/*TEST*/
printf("%d\n", source_length);
/*determine length of substring string*/
for (i=0; i<MAX_SUB_STRING_INPUT; i++) {
if (subString[i] != '\0')
substring_length++;
}
/*TEST*/
printf("%d\n", substring_length);
for (j=0; j<substring_length; j++) {
for (k=0; k<source_length-substring_length; k++) {
if (source[k] && subString[j] == 0) {
j++;
}
}
}
if (j == substring_length) {
printf("Output: \"%s\" is a substring of \"%s\"", subString, source);
}
else {
printf("Output: \"%s\" is NOT a substring of \"%s\"", subString, source);
}
optionStats[3]++;
return TRUE;
}