Examples of strchr() in C
Input:
str1 = "w3wiki"
ch = s
Output:
Character 's' is found at position: 4
The following examples illustrates how we can use strchr() in various scenarios.
Example 1:
The below example demonstrates how we can use strchr() function to check if the character exists in a given string or not and print its first occurence in C++.
// C program to demonstrate the use of strchr() function
#include <stdio.h>
#include <string.h>
int main()
{
// define a string
const char* str = "w3wiki";
// define a char ch to be searched in str
char ch = 's';
// Use strchr to find the first occurrence of the
// character 's'
const char* result = strchr(str, ch);
if (result != NULL) {
// Calculate the position by subtracting the base
// pointer from the result pointer
printf("Character '%c' found at position: %ld\n",
ch, result - str);
}
else {
printf("Character '%c' not found.\n", ch);
}
return 0;
}
Output
Character 's' found at position: 4
Time Complexity: O(n), where n is the length of the string str
Auxilliary Space: O(1)
Example 2:
The below example demonstrates how we can use strchr() function to parse the string until a given delimiter is found.
// C program to demonstrate the use of strchr()
#include <stdio.h>
#include <string.h>
int main()
{
// Original string containing username and password
const char* str = "w3wiki:abc@123";
// Delimiter to separate username and password
char delimiter = ':';
// Find the position of the delimiter in the string
char* delimiter_position = strchr(str, delimiter);
// If the delimiter is found in the string
if (delimiter_position != NULL) {
// Calculate the length of the username
size_t username_length = delimiter_position - str;
// Allocate memory for the username and copy the
// username part of the string
char username[username_length + 1];
strncpy(username, str, username_length);
// Null-terminate the username string
username[username_length] = '\0';
// The password starts right after the delimiter
char* password = delimiter_position + 1;
// Print the extracted username and password
printf("Username: %s\n", username);
printf("Password: %s\n", password);
}
else {
// If the delimiter is not found, print an error
// message
printf("Delimiter not found.\n");
}
return 0;
}
Output
Username: w3wiki Password: abc@123
Time Complexity: O(n)
Auxilliary Space: O(1)
strchr in C
The strchr() function in C is a predefined function in the <string.h> library. It is used to find the first occurrence of a character in a string. It checks whether the given character is present in the given string or not, if the character is found it returns the pointer to it otherwise it returns a null pointer indicating the character is not found in the string.
Contact Us