views:

131

answers:

1

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;

}
+1  A: 

I have a couple suggestions for you:

for (j=i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++);

Break this up; don't cram everything in the for control structure.

j = i;
k = 0;
for (;;) {
    if (t[k] == '\0') break;
    if (s[j] != t[k]) break;
    j++;
    k++;
}

Get better names for your variables.

haystack_inner_index = i; /* get a better name for `i` too */
needle_index = 0;
for (;;) {
    if (needle[needle_index] == '\0') break;
    if (haystack[haystack_inner_index] != needle[needle_index]) break;
    haystack_inner_index++;
    needle_index++;
}
pmg