strchr 實作 (strlen Implementation)

strchr 實作 (strlen Implementation)

strchr 實作 教學與筆記。

說明

尋找字串裡某字元。若有回傳字元第一次出現的指標,若無返回 NULL。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>

char* _strchr(char *s, char c) {
char *p = NULL;
while(*s) {
if(*s == c) {
p = s;
return p;
}
s++;
}
return p;
}

void main() {
char str[] = "hello";
char *p = str;

// print all address
while(*p) {
printf("%p\n", p);
p++;
}

printf("\n");

// search
char *ptr = _strchr(str, 'l');
printf("%p\n", ptr);
}

結果圖:

1
2
3
4
5
6
7
0x7ffdf60ba0b2
0x7ffdf60ba0b3
0x7ffdf60ba0b4
0x7ffdf60ba0b5
0x7ffdf60ba0b6

0x7ffdf60ba0b4
Author

Meow Lucian

Posted on

2019-07-30

Updated on

2022-07-04

Licensed under

Comments