#include <stdio.h>
#include <string.h>
int main(void){
char str[100]="Welcome to plus2net";
char *p; // declaring a pointer variable
p = strchr(str,'m');
printf("value :%c \n",*p); // output is m
printf("Address :%d",p); // output is address of m
return 0;
}
In the code above in first printf(), we are printing the value at the address stored in our pointer variable p. In second printf() we are printing the address.
#include <stdio.h>
#include <string.h>
int main(void){
char str[100]="Welcome to plus2net";
char *p;
p = strchr(str,'m');
printf("Position :%d",p-str+1);
return 0;
}
The output of above code is here
Position :6
In above code, by subtracting the pointer of main string and by adding 1 to it , we will get the position of matching character related to main string.
strchr()
string function.
strchr(main_string, search_string);
Note that strchr() returns the address of first matching char, so we have to use one pointer variable to store the return value of this function. #include <stdio.h>
#include <string.h>
int main(void){
char str[100]="Welcome to plus2net";
char *p;
p = strchr(str,'m');
printf("Position :%d , %s",p-str+1,p);
return 0;
}
Output is here
Position :6, me to plus2net
This example demonstrates how to find the first occurrence of a character in a string using strchr().
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Welcome to plus2net";
char *result = strchr(str, 'o');
if (result != NULL) {
printf("First occurrence of 'o' is at position: %ld\n", result - str);
} else {
printf("Character not found.\n");
}
return 0;
}
Output:
First occurrence of 'o' is at position: 4
---
Use strchr() to check whether a specific character exists in the string.
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "C programming is fun!";
char ch = 'p';
if (strchr(str, ch)) {
printf("The character '%c' exists in the string.\n", ch);
} else {
printf("The character '%c' was not found.\n", ch);
}
return 0;
}
Output:
The character 'p' exists in the string.
---
This example allows the user to input a string and a character to search for using strchr().
#include <stdio.h>
#include <string.h>
int main() {
char str[100], ch;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove newline character
printf("Enter a character to search for: ");
scanf("%c", &ch);
if (strchr(str, ch)) {
printf("The character '%c' was found in the string.\n", ch);
} else {
printf("The character '%c' was not found in the string.\n", ch);
}
return 0;
}
Output:
Enter a string: Welcome to C programming
Enter a character to search for: g
The character 'g' was found in the string.