Which C library function returns a pointer to the last occurrence of a specified character within a null-terminated string?

C# Programming Strings Difficulty: Easy
Choose an option
  • A
    strnstr()
  • B
    laststr()
  • C
    strrchr()
  • D
    strstr()
  • E
    None of the above

Answer

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:

  • Strings are null-terminated char arrays.
  • You want the last position of a character.
  • Standard C library is available.

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:

  • strnstr: Non-standard and substring-oriented, not last-character search.
  • laststr: Not a standard function.
  • strstr: Finds substrings, not single characters.

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
No comments yet. Be the first to comment!
Join Discussion