In the C standard library, which function finds the first occurrence of a given substring within another string (i.e., searches for one string inside a larger string)?

Difficulty: Easy

Correct Answer: strstr()

Explanation:


Introduction / Context:
String searching is a common task. The C library offers functions for locating characters and substrings. Choosing the correct function saves time and avoids writing error-prone custom loops for pattern search.


Given Data / Assumptions:

  • The goal is to find a substring (needle) inside another string (haystack).
  • Null-terminated strings (char*) are used.
  • We want the first occurrence.


Concept / Approach:
strstr(haystack, needle) returns a pointer to the first occurrence of needle in haystack, or NULL if not found. For single-character searches, use strchr; for the last occurrence of a character, use strrchr; strnset is a non-standard function for filling portions of a string, not searching.


Step-by-Step Solution:
Call strstr(h, n) where h is the larger string, n is the substring.Check the return value: non-NULL indicates success and points at the match.If you need the index, subtract h from the returned pointer.Handle NULL safely to avoid dereferencing invalid pointers.


Verification / Alternative check:
Test with strstr("embedded systems", "bed") which returns a pointer to the substring starting at index 2.


Why Other Options Are Wrong:

  • strchr: finds a character, not a substring.
  • strrchr: finds the last occurrence of a character.
  • strnset: sets characters; not a search function.


Common Pitfalls:
Confusing character search with substring search. Also, ensure needle is not an empty string, which per the standard makes strstr return haystack.


Final Answer:
strstr().

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion