strlen:
用于求字符串长度,从首字符开始,到'\0'结束,'\0'不计入总长度。
函数实现:
1
2
3
4
5
6
7
|
size_t my_strlen( const char * ptr) { assert (ptr); const char * ptx = ptr; while (*(++ptx)); return ( size_t )(ptx - ptr); } |
strcmp:
用于比较两个字符串大小,注意大小并不是指字符串长度,而是从第一个字符开始比较,比较字符的大小。该函数返回的是一个int值,不同编译器,返回的值是不一样。但是正负是一致的,当第一个大于第二个,返回正值,小于则返回负值,相等返回0。
函数实现:
1
2
3
4
5
6
|
int my_strcmp( const char * str1, const char * str2) { assert (str1 && str2); while ((!(*str1 - *str2)) && ((*(str1++)) * (*(str2++)))); return ( int )(*str1 - *str2); } |
strcpy:
用于复制字符串。
函数实现:
1
2
3
4
5
6
7
|
char * my_strcpy( char * dest, const char * source) { assert (dest && source); char * result = dest; while (*(dest++) = *(source++)); return result; } |
strcat:
用于在目标字符串末尾追加一个字符串。
函数实现:
1
2
3
4
5
6
7
8
9
|
char * my_strcat( char * a, const char * b) { assert (a && b); char * tmp = a; while (*(++a)); while (*(a++) = *(b++)); *a = '\0' ; return tmp; } |
strstr:
用于在一个字符串内寻找另一个字符串。这于KMP算法有关。
函数实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
const char * my_strstr( const char * a, const char * b) //a为长字符串 b为短字符串 { char * cp = ( char *)a; char * s1; char * s2; if (!*b) return a; while (*cp) { s1 = cp; s2 = ( char *)b; while (*s1 && *s2 && !(*s1 - *s2)) { s1++; s2++; } if (!*s2) return cp; cp++; } return NULL; } |
atoi:
这个函数很有意思,它会把字符串的数字串转化为int值。
函数实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
int my_atoi( const char * str) { assert (str); int num = 0; int result = 0; const char * tmp = str; while (*str && *str != '.' ) { num++; str++; } while (num--) { result += (*tmp - '0' ) * ( int ) pow (10, num); tmp++; } return result; } |
strncpy
,strncmp
,strncat
:
三个函数都是限制了字符个数,功能是一样的。
函数实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
char * my_strncpy( char * dest, const char * sou, size_t num) { assert (dest && sou); char * tmp = dest; while ((num--) && (*(dest++) = *(sou++))); return tmp; } char * my_strncat( char * a, const char * b, int n) { assert (a && b); char * tmp = a; while (*(++a)); while ((n--) && (*(a++) = *(b++))); *a = '\0' ; return tmp; } int my_strncmp( const char * str1, const char * str2, int n) { assert (str1 && str2); while ((!(*str1 - *str2)) && ((*(str1++)) * (*(str2++))) && (n--)); return ( int )(*str1 - *str2); } |
总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!
原文链接:https://blog.csdn.net/roseisbule/article/details/122916028