Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
string
strchr
communitycreator

What is strchr in C?

Danil

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

The strchr() function is a built-in library function declared in the string.h header file.

It finds the first occurrence of a character in a string and returns a pointer to the found character, or null pointer, if no such character is found.

Syntax

strchr() takes string as a first argument, character as a second, and returns a pointer to char.

char* strchr(const char* str, int ch);

Cases

Case 1

const char* string = "hello";
strchr(string, 'l'); // returns pointer to the third character of the string
1 of 3

Case 2

const char* string = "hello";
strchr(string, 'a'); // returns NULL
1 of 6

Code

#include <stdio.h>
#include <string.h>
int main()
{
const char *str = "To be, or not to be: that is the question";
char target = 't';
const char *result = str;
// Find the first occurence of the target
result = strchr(result, target);
while (result != NULL) {
printf("Found '%c' starting at '%s'\n", target, result);
// Increment result, otherwise we'll find target at the same location
++result;
// Find the next occurence of the target
result = strchr(result, target);
}
}

RELATED TAGS

c
string
strchr
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring