Question

How do I find the index of a substring in a string using C?

Answer and Explanation

To find the index of a substring within a string in C, you can use the strstr() function along with some basic pointer arithmetic. The strstr() function locates the first occurrence of a substring within another string.

Here's how you can do it:

1. Include Necessary Header:

- First, you need to include the string.h header file which contains the strstr() function.

2. Use strstr() Function:

- The strstr() function has the following signature:

char strstr(const char haystack, const char needle);

- It takes two arguments: haystack is the string in which you search, and needle is the substring you are looking for.

- If needle is found within haystack, it returns a pointer to the first character of the found substring. Otherwise, it returns NULL.

3. Calculate the Index:

- If strstr() returns a non-NULL pointer, you can calculate the index by subtracting the base address of the haystack string from the pointer returned by strstr().

4. Handle Not Found Scenario:

- Remember to check for NULL return value from strstr(), and provide an appropriate handling if the substring is not found.

5. Example Implementation:

Here's a C code example:

#include <stdio.h>
#include <string.h>

int findSubstringIndex(const char haystack, const char needle) {
    char ptr = strstr(haystack, needle);
    if (ptr == NULL) {
        return -1; // Substring not found
    }
    return ptr - haystack; // Calculate the index
}

int main() {
    const char text = "This is a sample string for substring search.";
    const char sub = "sample";
    int index = findSubstringIndex(text, sub);

    if (index != -1) {
        printf("Substring found at index: %d\\n", index);
    } else {
        printf("Substring not found\\n");
    }

    const char sub2 = "notpresent";
    int index2 = findSubstringIndex(text, sub2);
    if (index2 != -1) {
        printf("Substring found at index: %d\\n", index2);
    } else {
        printf("Substring not found\\n");
    }
    return 0;
}

6. Explanation of the Code:

- The findSubstringIndex function takes the haystack string and needle substring as inputs.

- It calls strstr() to find the substring.

- If the substring is found, the function calculates the index by pointer subtraction and returns it.

- If the substring is not found, it returns -1.

By understanding the strstr() function and pointer arithmetic, you can easily find the index of a substring within a string in C.

More questions