作用:在字符串中找到一个字符首次出现的位置。

实现机制:循环遍历整个字符串,找不到就向后移动,直至到达’\0’,返回NULL,如果找到就返回首次出现字符的地址。

函数实现

char* my_strchr(const char* dest, char f)
{
	assert(dest != NULL);

	while (*dest != f)
	{
		dest++;
	}
	if (*dest != '\0')
	{
		return dest;
	}
	return NULL;
}

参考代码如下

#include <stdio.h>
#include <assert.h>

char* my_strchr(const char* dest, char f)
{
	assert(dest != NULL);

	while (*dest != f)
	{
		dest++;
	}
	if (*dest != '\0')
	{
		return dest;
	}
	return NULL;
}

int main()
{
	char arr[1024] = "hello world!";
	char find = 'l';
	printf("%s\n", my_strchr(arr, find));
	return 0;
}

运行结果如下
string.h库函数的实现---strchr

相关文章:

  • 2022-12-23
  • 2021-08-26
  • 2022-01-12
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
猜你喜欢
  • 2021-05-15
  • 2022-12-23
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
  • 2022-12-23
相关资源
相似解决方案