C strings: which standard library function finds the last occurrence of a character in a string? Pick the correct function name used to search from the end.

Difficulty: Easy

Correct Answer: strrchr()

Explanation:


Introduction / Context:
This question assesses knowledge of common string functions in the C standard library, specifically how to locate characters within a NUL-terminated byte string.


Given Data / Assumptions:

  • The target is to find the last occurrence of a given character.
  • Input is a standard C string terminated by a '\\0' byte.
  • We want the standard function provided by string.h.


Concept / Approach:

The correct function is strrchr(const char *s, int c). It searches for the last occurrence of c (converted to unsigned char) in the string s, including the terminating '\\0' if c is '\\0'. It returns a pointer to the located character or NULL if not found.


Step-by-Step Solution:

1) Include <string.h>. 2) Call p = strrchr(s, ch). 3) If p != NULL, p points to the final occurrence from the right. 4) Use the pointer for slicing or index math as needed.


Verification / Alternative check:

Compare with strchr which finds the first occurrence; the extra 'r' in strrchr mnemonically stands for “reverse/last”.


Why Other Options Are Wrong:

strnchar, strchar, strrchar: These are not standard C functions.


Common Pitfalls:

  • Confusing strchr and strrchr.
  • Forgetting that searching for '\\0' is allowed and returns a pointer to the terminator.


Final Answer:

strrchr()

Discussion & Comments

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