Challenge: Locate the First Occurrence

Test your knowledge by solving this coding challenge.


For this challenge, we’re moving away from problems we can solve by a two-pointers approach and instead try something different.

Problem statement

You will have to implement the C library function strchr. This function takes a string and a character as inputs. It returns a pointer to the first occurrence of the character in the string. If the character doesn’t occur in the string, it returns NULL.

The function will look like this:

char* mystrch(char* str, int c)

Example input and output

Input 1:

str = "abbbcd"
c = 'b'

Output 1:

Pointer to str[1]

str[1] is the first occurrence of b in str.

Input 2:

str = "abbbcd"
c = 'x'

Output 2:


x does not appear in “abbbcd”.


Please spend some time thinking about how to approach and solve this problem. Try to solve it on your own before reading the solution.

The tests will display NULL as (nil). The tests will also show the index of the character together with the pointer address.

For example:

0xabcdef 5

This test output means that the pointer holds the 0xabcdefg address and points to str[5].

Get hands-on with 1200+ tech skills courses.