作用:在字符串中找到一个字符首次出现的位置。
实现机制:循环遍历整个字符串,找不到就向后移动,直至到达’\0’,返回NULL,如果找到就返回首次出现字符的地址。
函数实现:
char* my_strchr(const char* dest, char f)
{
assert(dest != NULL);
while (*dest != f)
{
dest++;
}
if (*dest != '\0')
{
return dest;
}
return NULL;
}
参考代码如下:
出现错误:
- 访问限定符const在.c文件中会出现警告,可正常运行;在.cpp文件中会报错,无法运行;
- 访问越界,在找字符串中不存在的字符时,循环中没有终止条件;
#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;
}
运行结果如下:
修改后
#include <stdio.h>
#include <assert.h>
char* my_strchr(char* dest, char f)
{
assert(dest != NULL);
while (*dest != f)
{
if (*dest == '\0')
{
return NULL;
}
dest++;
}
return dest;
}
int main()
{
char arr[1024] = "hello world!";
char find = 'l';
printf("%s\n", my_strchr(arr, find));
return 0;
}