“This is the 12th day of my participation in the Gwen Challenge in November. See details of the event: The Last Gwen Challenge 2021”.

The STRCHR () function

In C, you can use the STRCHR () function to find if a string contains a character. Its function prototype is:

char *strchr(const char *str, int c)

It takes two parameters, the first parameter is the string to look for and the second parameter is the character to look for in the string. The return value is a pointer to the first occurrence of a character in the string, or NULL if no character is found in the string.

It can be used as follows:

int main(int argc, char *argv[])
{
	char str1[]="abcdefgabcdef";
	char *str2;
	
	puts(str1);
	
	str2 = strchr(str1,'e');
	if(str2 == NULL)
		puts("not find");
		
	puts(str2);	

	system("pause");
	return 0;
}
Copy the code

First define a string, and then use the STRCHR () function to find if the character e is contained in string 1. The STRCHR () function takes two arguments. The first argument is the string to look up and the second argument is the character to look up. Returns the position of the first occurrence of the character if it contains the character sought, or a null pointer if it does not.

The string 1 contains two characters e, but the position returned is the first occurrence of E.

Returns a null pointer if the character being looked for is not contained in the string.

The STRRCHR (” c: “() function

If the STRRCHR () function does what the STRCHR () function does, it looks for a character in the string, but it returns the position of the last contained character in the string. The function prototype is:

char *strrchr(const char *str, int c)

It takes two parameters, the first parameter is the string to look for and the second parameter is the character to look for in the string. The return value is a pointer to the last occurrence of a character in the string, or NULL if no character is found in the string.

int main(int argc, char *argv[])
{
	char str1[]="abcdefgabcdef";
	char *str2;
	
	puts(str1);
	
	str2 = strrchr(str1,'e');
	if(str2 == NULL)
		puts("not find");
		
	puts(str2);	

	system("pause");
	return 0;
}
Copy the code

Change the STRCHR () function in the above example to STRRCHR () and print the following:

The string 1 contains two characters e, but it returns the position where e was last seen.

Similarly, if the string does not contain the character being searched, a null pointer is returned.

The STRCHR () and STRRCHR () functions are both used to find if a string contains a particular character. The only difference is that the STRCHR () function returns the position at which the character first appears in the string. The STRRCHR () function returns the position of the last occurrence of a character in the string.