1.描述
-
const char * strchr ( const char * str, int character );
char * strchr ( char * str, int character );
- 字元比對函數,成功傳回在str中的位址,失敗傳回NULL,\0也作為比對的字元。
- 庫函數缺乏安全檢查,空指針會崩潰。
- 通過定義字元為Int型,通過比較ascii碼來實作傳入資料。
2.代碼展示
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
char* mystrchr( char*str, int character)
{
assert(str);
while (*str)
{
if (*str == character)
return str;
++str;
}
if (*str == character)
return str;
return NULL;
}
void test4()
{
char* ret;
char arr1[] = "abcdef";
//char *arr1 = NULL;
int n1 ='\0';
ret = strchr(arr1, n1);
printf("%p %s\n", ret, ret);
int n2 = '\0';
char arr2[] = "abcdef";
//char *arr2 = NULL;
ret = mystrchr(arr2, n2);
printf("%p %s\n", ret, ret);
}
int main()
{
test4();
system("pause");
return 0;
}