Difficulty: Easy
Correct Answer: strrchr()
Explanation:
Introduction / Context:
Working with strings often requires locating characters from either end. The C library provides separate functions for the first and last occurrences. Picking the right one avoids manual reverse scans and reduces bugs.
Given Data / Assumptions:
Concept / Approach:
strrchr(s, c) scans the string s and returns a pointer to the last occurrence of character c, or NULL if c does not appear. For first occurrence, use strchr; for substring search, use strstr. Non-standard names like strnstr may exist on some platforms but find substrings, not necessarily last characters, and are not in the C standard.
Step-by-Step Solution:
Call strrchr with the target string and character.Check for NULL to handle not-found cases safely.If non-NULL, compute index by pointer subtraction if needed.Use the returned pointer for further processing (e.g., splitting).
Verification / Alternative check:
Example: strrchr("banana", 'a') returns a pointer to the final 'a' (index 5).
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting that the null terminator '\0' can also be searched; strrchr(s, '\0') returns a pointer to the terminator at the end of s.
Final Answer:
strrchr().
Discussion & Comments