Find a Substring in a String in C

In C, you can find a substring within a string using various methods, including standard library functions like strstr() and strchr(), as well as custom implementations. These functions help locate a smaller string (substring) inside a larger string (main string) and return its position or pointer.

In this tutorial, we explore multiple ways to find a substring in C with examples.


Examples of Finding a Substring

1. Using strstr() Function to Find Substring in a String

In this example, we use the strstr() function, which is part of the C standard library. It returns a pointer to the first occurrence of the substring in the given string. If the substring is not found, it returns NULL.

main.c

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

int main() {
    char str[] = "Hello, welcome to C programming!";
    char sub[] = "welcome";

    // Using strstr() to find substring
    char *pos = strstr(str, sub);

    if (pos != NULL) {
        printf("Substring found at position: %ld\n", pos - str);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}

Explanation:

  1. We declare and initialize a string str with “Hello, welcome to C programming!”.
  2. We define another string sub containing the substring “welcome”.
  3. The strstr() function is used to locate sub in str. If found, it returns a pointer to the first occurrence.
  4. We check if strstr() returns NULL. If not, we calculate the position by subtracting the base address of str from the found pointer.
  5. The position is printed using printf().

Output:

Substring found at position: 7

2. Using strchr() to Find a Character

In this example, we use strchr() to find the first occurrence of a single character in a string.

main.c

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

int main() {
    char str[] = "AppleBanana";
    char ch = 'a';

    // Using strchr() to find the first occurrence of a character
    char *pos = strchr(str, ch);

    if (pos != NULL) {
        printf("Character '%c' found at position: %ld\n", ch, pos - str);
    } else {
        printf("Character not found.\n");
    }

    return 0;
}

Explanation:

  1. We declare a string str containing a sentence.
  2. We specify a character ch to search for.
  3. The strchr() function is used to find the first occurrence of ch.
  4. If strchr() returns a valid pointer, we calculate and print its position.

Output:

Character 'C' found at position: 6

3. Implementing a Custom Function to Find a Substring

If we do not want to use built-in functions, we can manually search for a substring in a string using a custom function.

main.c

</>
Copy
#include <stdio.h>

int findSubstring(const char *str, const char *sub) {
    int i, j;
    for (i = 0; str[i] != '\0'; i++) {
        for (j = 0; sub[j] != '\0'; j++) {
            if (str[i + j] != sub[j]) {
                break;
            }
        }
        if (sub[j] == '\0') {
            return i;
        }
    }
    return -1;
}

int main() {
    char str[] = "AppleBananaCherry";
    char sub[] = "Banana";

    int pos = findSubstring(str, sub);
    
    if (pos != -1) {
        printf("Substring found at position: %d\n", pos);
    } else {
        printf("Substring not found.\n");
    }

    return 0;
}

Explanation:

  1. The findSubstring() function uses nested loops to compare characters from str and sub.
  2. It iterates over str and checks if the substring matches character by character.
  3. If all characters of sub match, the function returns the starting index.
  4. If no match is found, the function returns -1.
  5. In main(), we pass a test string and substring, and print the result.

Output:

Substring found at position: 5

Conclusion

In this tutorial, we explored different ways to find a substring in C:

  1. Using strstr() to find substrings.
  2. Using strchr() to find a single character.
  3. Implementing a custom function for substring search.