C language STRCHR () function: Find out where a character first appears in a string
Header files: #include <string.h>
STRCHR () is used to find the first occurrence of a character in a string, and its prototype is:
char * STRCHR (const char *STR, int c);
"Argument" Str is the string to find, and C is the character to find.
STRCHR () will find the address of character C for the first time in the STR string, and then return the address.
Note: The end of the string Str NUL is also included in the retrieval range, so a character in the STR group can also be positioned.
Return value returns the address of the character if the specified character is found, otherwise NULL.
The returned address is a string of randomly assigned addresses in memory plus the character you are searching for in the string position. The first occurrence of the character in the string is I, then the returned address can be interpreted as STR + i.
Tip: You can use the STRRCHR () function if you want to find the last occurrence of a character in a string.
The instance looks for the first occurrence of character 5.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *s = " 0123456789012345678901234567890 ";
char *p;
p = STRCHR (S, ' 5 ');
printf ("%ld\n", s);
printf ("%ld\n", p);
System ("pause");
return 0;
}
Output results:
C language STRRCHR () function: Find the last occurrence of a character in a string
Header files: #include <string.h>
The STRRCHR () function is used to find the last occurrence of a character in a string, and its prototype is:
char * STRRCHR (const char *STR, int c);
"Argument" Str is the string to find, and C is the character to find.
STRRCHR () will find the address of the last occurrence of character C in the Str string, and then return the address.
Note: The end of the string Str NUL is also included in the retrieval range, so a character in the STR group can also be positioned.
Return value if found, returns the last occurrence of the character, or NULL.
The returned address is a string of randomly assigned addresses in memory plus the character you are searching for in the string position. The first occurrence of the character in the string is I, then the returned address can be interpreted as STR + i.
Tip: If you want to find the first occurrence of a character in a string, you can use the STRCHR () function.
Instance: Find the position where character 5 was last seen.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *s = " 0123456789012345678901234567890 ";
char *p;
p = STRRCHR (S, ' 5 ');
printf ("%ld\n", s);
printf ("%ld\n", p);
System ("pause");
return 0;
}
Execution results: