strchr与strrchr

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

用来找出参数s字符串中第一个出现的参数c地址,然后将该字符出现的地址返回

using namespace  std;
#include<iostream>
#include<assert.h>
char* Mystrchr(char* dest, int c){
	assert(dest&&c);
	while (*dest){

		if (*dest == c){
			return dest;
		}
		dest++;
	}

	return NULL;
}
int main(){
	char  arr1[] = "I am a girl";
	char  s = 'a';
	char* ret=Mystrchr(arr1,s);
	if ((ret!=NULL)&&(*ret==s)){
		
		printf("字符%c第一次出现的位置:%s\n",s, ret);

	}else{
		printf("没找到\n");
	}
	
	system("pause");
	return 0;
}

结果:

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

用来找出参数s字符串中最后一个出现的参数c地址,然后将该字符出现的地址返回
 

using namespace  std;
#include<iostream>
#include<assert.h>

char * Mystrrchr(char* dest, int c){
	char* ptr = dest;
	int count = 0;
	assert(dest&&c);
	while (*dest){

		if (*dest == c){
			count++;
			ptr = dest;
		}
		dest++;
	}
	printf("%d\n", count);
	return ptr;
}

int main(){
	char  arr1[] = "I am a girl";
	char  s = 'a';
	char* ret = Mystrrchr(arr1, s);
	if (*ret == s){

		printf("字符%c最后出现的位置:%s\n", s, ret);

	}
	else{
		printf("没找到\n");
	}
	
	system("pause");
	return 0;
}

结果:

猜你喜欢

转载自blog.csdn.net/zhangyan323/article/details/84978364