The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
strchr() is one of the inbuilt string function in c programming which is used to find the first occurrence of a character chr in a string str.
The following diagram clearly illustrate the working principle of strchr() inbuilt string function in C.
In the above diagram strchr() takes two parameters say str and chr. str is a string whereas chr is a character. If a character in chr presents in a string str, then strchr() will return the string str starting from a character in chr, If a character is not found in a string, then strchr() returns null
strchr (str, chr);
Let us work through strchr() function. In the following program we will find the first occurrence of a character chr in a string str.
#include <stdio.h> #include<string.h> int main() { char str1[] = "Bangalore", chr = 'g'; char *chrpos; chrpos = strchr(str1, chr); if(chrpos) printf("%s", chrpos); return 0; }
galore
The above program prints galore as an output as g is a character we seeks in a string bangalore.
Let us print the string from the first occurrence of a character chr without using inbuilt string function strchr().
#include <stdio.h> #include<string.h> int main() { char str[] = "Bangalore", chr = 'g'; char str1[12], i, j, k = 0; for(i=0; str[i]!='\0'; i++){ if(str[i]==chr) { for(j=i; str[j]!='\0'; j++){ str1[k] = str[j]; k++; } str1[k]='\0'; break; } } printf("%s",str1); return 0; }
galore
The above program looks verbose but yields same the result.
When strchr() fails to find the occurrence of a character chr in a string str, then it returns null string.
#include <stdio.h> #include<string.h> int main() { char str1[] = "Bangalore", chr = 'z'; char *chrpos; chrpos = strchr(str1, chr); printf("%s", chrpos); return 0; }
(null)
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019