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:
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:
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