OneBite.Dev - Coding blog in a bite size

find the index of a substring within a string in C

Code snippet on how to find the index of a substring within a string in C

  int index_of(const char * str, const char * substr) {
    if (!str || !substr) return -1;
    
    const char * pos = strstr(str, substr);
    if (pos) return pos - str;
    else return -1;
  }

This code will find the index of a substring within a string. First, it checks to make sure that the string and substring variables are not empty. If they are, we return -1. Then, we search the string and return the index of the first occurrence of the substring. If the substring is not found, the code will return -1.

c