K&R C Programs Exercise 4-1

Exercise 4-1. Write the function strindex(s,t) that returns the position of the rightmost occurrence of t in s, or -1 if there is none.

The K&R strindex in Section 4.1 returns the leftmost match by scanning left-to-right and returning at the first hit. For the rightmost match there are two symmetric approaches: scan right-to-left and return at the first hit, or scan left-to-right and keep overwriting last with every hit. Both are shown below. Right-to-left is the direct analogue of the original and slightly more efficient (stops as soon as it finds the rightmost), but left-to-right is easier to reason about for correctness.

Solution

/* K&R Exercise 4-1 — strindex: rightmost occurrence of t in s
 * Compile: gcc -ansi -Wall ex4-1.c -o ex4-1 */
#include <stdio.h>
#include <string.h>

/* Scan right-to-left — return at first match (= rightmost) */
int strindex_right(char s[], char t[])
{
    int i, j, k;
    int tlen = strlen(t);
    for (i = strlen(s) - tlen; i >= 0; i--) {
        for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
            ;
        if (k > 0 && t[k] == '\0')
            return i;
    }
    return -1;
}

/* Scan left-to-right — keep updating last */
int strindex_last(char s[], char t[])
{
    int i, j, k, last = -1;
    for (i = 0; s[i] != '\0'; i++) {
        for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++)
            ;
        if (k > 0 && t[k] == '\0')
            last = i;
    }
    return last;
}

int main(void)
{
    printf("%d\n", strindex_right("hello world hello", "hello")); /* 12 */
    printf("%d\n", strindex_right("abcabc", "bc"));               /*  4 */
    printf("%d\n", strindex_right("abcabc", "xyz"));              /* -1 */
    printf("%d\n", strindex_right("aaa", "a"));                   /*  2 */
    printf("%d\n", strindex_last("hello world hello", "hello"));  /* 12 */
    return 0;
}

Compile and Run

gcc -ansi -Wall ex4-1.c -o ex4-1
./ex4-1

Sample Output

12
4
-1
2
12

What This Exercise Teaches

  • Symmetric algorithms — searching right-to-left is the exact mirror of left-to-right; the logic is identical, only the loop direction and starting point change
  • Two strategies for “last match” — early exit (right scan) vs keep-updating (left scan); same result, different efficiency
  • Empty string edge case — if t is "", k == 0 on every iteration so the k > 0 guard correctly returns -1 rather than a spurious match

Set Up Your C Environment

← Exercise 3-6  | 
Chapter 4 Solutions  | 
Exercise 4-2 →

Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie

1 comment on “K&R C Programs Exercise 4-1

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>