CodeBlanks Logo Icon CodeBlanks

strstr

Learn to search for a substring with strstr.

strstr: searching for a substring

The strstr function searches for one string inside another. Its signature is char *strstr(const char *s, const char *sub). It comes with the <string.h> header.

char *p = strstr("merhaba dunya", "dunya");
// p points at the "dunya" part

To get the starting index of the match, you again use p - s. It returns NULL if not found. strchr searches for a single character; strstr searches for a multi-character substring.

strstr example: computing the index

By subtracting the start of the string from the pointer that strstr returns, you get the substring's starting index.

char text[] = "merhaba dunya";
char *p = strstr(text, "dunya");
long index = p - text;
// index = 8

Here the "dunya" substring starts at index 8. Always check that p is not NULL before subtracting. This pattern is very useful to find where a word appears in a string.

Practice Print the index of the "dunya" substring

Use strstr to find the starting index of the "dunya" substring in "merhaba dunya" and print it with printf. You must include the <string.h> header.

Starter code

main.c
#include <stdio.h>

int main(void) {
    char text[] = "merhaba dunya";
    /* Find the starting index of "dunya" with strstr and print it */
    return 0;
}

Sample solution

main.c
#include <string.h>
char *p = strstr(text, "dunya");
if (p != NULL) {
    printf("%ld\n", (long)(p - text));
}

Expected output

8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match function to task

Term Meaning
strstr(s, sub) Searches substring
strchr(s, c) Searches character
strcmp(a, b) Compares
strlen(s) Returns length

2 What does strstr("merhaba", "ha") return?

  • The value 0
  • Pointer starting at "ha" Correct answer
  • The index of the first 'h'
  • NULL

Explanation: strstr returns a pointer to the start of the match.

3 Fill in the blank: strstr call

Question
char *p = ____(text, "dunya");
Answer
char *p = strstr(text, "dunya");

Explanation: strstr searches a substring.

All lessons in Beginner