I'm stuck on part of my homework, I had to find the rightmost occurrence of a substring inside of a string. I have the first part done (can find substring in single word strings), but now I am having trouble with the second part. I have to use a modified version of getline in order to allow multi-word strings (aka with spaces). Here's the unmodified code of getline() and the modified strindex() as well (respectively). I'd love an explanation as well, I have trouble understanding written code sometimes.
EDIT: So I updated my code, here it is :)
/* string index */
int strindex(char str[], char substr[]){
int str_idx, sub_idx, k, c = -1;
for (str_idx = 0; str[str_idx] != '\0'; str_idx++) {
for (sub_idx = str_idx, k = 0; substr[k] != '\0' && str[sub_idx] == substr[k]; sub_idx++, k++)
;
if (k > 0 && substr[k] == '\0')
c = str_idx;
}
return c;
return -1; //never reached?
}
/* getline
*
* Variable Dictionary
* ctchars - character counter, increments once each time getchar() is called
* str_idx - current index of the string, starts at 0, increments with loop
*
*/
getline(char str[], int lim){
int ctchars, str_idx = 0;
ctchars=getchar();
for (str_idx; str_idx<lim-1 && ctchars !=EOF && ctchars!='\n'; ++str_idx)
str[str_idx] = ctchars;
if (ctchars == '\n') {
str[str_idx] = ctchars;
++str_idx;
}
str[str_idx] = '\0';
return str_idx;
}