Find Index of Substring in String in C Language

To find the index of given substring in a string, iterate over the indices of this string and check if there is match with the substring from this index of this string in each iteration.

C Program

In the following program, we take a string in str and substring in substr, take a for loop to iterate over the indices of string str, check if substring is present from this index.

Refer C For Loop tutorial.

main.c

#include <stdio.h>

int main() {
    char str[30] = "apple banana";
    char substr[30] = "bana";

    int index = -1;
    for (int i = 0; str[i] != '\0'; i++) {
        index = -1;
        for (int j = 0; substr[j] != '\0'; j++) {
            if (str[i + j] != substr[j]) {
                index = -1;
                break;
            }
            index = i;
        }
        if (index != -1) {
            break;
        }
    }
    
    printf("Index of first occurrence  : %d\n", index);
    return 0;
}

The outer For Loop is used to iterate over the indices of this string.

The inner For Loop is used if the substring matches with the string from this index. If substring matches, then this index is the index of the first occurrence of the substring in this string.

Output

Index of first occurrence  : 6
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to find the index of first occurrence of a substring in a string, with examples.