模拟实现strchr

C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置
该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//模拟实现strchr
char* Strchr(const char* str, size_t num){
	assert(str);
	char *ap=(char*)str;        //强制转换
	char Anum = (size_t)num;	
	char *address=NULL;         //定义一个指针变量NULL,后面用来存str的当前地址
	while (*ap!='\0'){
		address=ap;
		if (Anum==*ap){
			return address;
		}
		ap++;
	}
	if (*ap == '\0'){
		return NULL;
	}
}
int main(){
	char str1[] = "This is a simple string";
	char *p = Strchr(str1, 's');
	printf("%p\n", p);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43755544/article/details/88317294