返回首页   进站必读

8.8 strchr/strstr


8.8 strchr/strstr

搜索字符串

#include <string.h>
char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);
返回值:如果找到字符c,返回字符串s中指向字符c的指针,如果找不到就返回NULL

作用:查找字符串s中首次出现c的位置
举例:

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
	char str[] = "This is a string!";
	char c = 'r';

	printf("%s\n", strchr(str, c));
    
	return 0;
}

#include <string.h>
char *strstr(const char *haystack, const char *needle);
返回值:如果找到子串,返回值指向子串的开头,如果找不到就返回NULL

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
	char *s1 = "This is a string!";
	char *s2 = "string";
	char *p;

	p = strstr(s1, s2);
	if (p)
		printf("%s\n", p);
	else
		printf("Not Found!");

	return 0; 
}