您的位置:首页 > 其它

C字符串——库函数系列(strlen、strcat、strcpy、strcmp)

2017-08-18 10:58 1811 查看


C字符串——库函数系列(strlen、strcat、strcpy、strcmp)

一定义:

字符串:字符串是由零个或者多个字符组成的有限串行;

子串:字符串中任意个连续的字符组成的子序列,并规定空串是任意串的子串,字符串本身也是子串之一;“abcdefg”,”abc“就是其子串,但是“ade”不属于子串范围。

子序列:不要求字符连续,但是其顺序与其在主串中相一致;上例中,“abc”与“ade”都属于子序列范围;

二:C风格字符串包括两种:

1)字符串常量---以双引号括起来的字符序列,编译器自动在其末尾添加一个空字符。

2)末尾添加了’0‘的字符数组;

 三:标准库提供的字符串处理函数:

 注意:

1、自定义str库函数时,首先要明确接收的参数是否为空(assert),这样可有效避免bug;

2、对函数的参数要尽量多的应用const,以避免无意间修改了字符串。

3、要自行添加字符串的结束符‘\0’。

1)自定义实现strlen函数的功能;



1 //附带评分标准
2 int strlen(const char* src)//const 2'
3 {
4     assert(str != NULL); // 3'
5     int count =0;
6
7     while(*str++ != '\0') //2'
8         count++;
9     return count;//3'
10 }


2)自定义实现strcat函数的功能;



1 char* strcat(char *strD, const char *strS)
2 {
3     assert(strD != NULL && strS != NULL);
4     char* address = strD;
5
6     while(*strD != '\0')//走到末尾
7         strD ++;
8
9     while(*strD++ = *strS++);//cat
10     return address; //attention
11 }


3)自定义实现strcmp函数的功能;



1 int strcmp(const char *s1, const char *s2)
2 {
3     assert(s1 != NULL && s2 != NULL);
4     int ret;
5     ////s1 ="abcd"; s2 = "abcde";则ret = 0-'e' < 0
6     while( !(ret = *(unsigned char*)s1 - *(unsigned char*)s2) && *s1)
7     {
8         s1 ++;
9         s2 ++;
10     }
11
12     if(ret < 0) return -1;
13     else if( ret >0) return 1;
14     return 0;
15 }


4)自定义实现strcpy函数的功能;



1 char* strcpy(char *strD, const char *strS)
2 {
3     assert(strD != NULL && strS != NULL);
4     char* address = strD ;
5
6     //attention此处,若*strS为’\0‘,则其先赋值给strD,故最后不需要再添加'\0'
7     while(*strD++ = *strS++);
8
9     return address;
10 }


测试函数如下:



1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4
5 int main(int argc, char const *argv[])
6 {
7     char s1[] = "helloworld";
8     printf("%d\n", s1);
9
10     char s2[100] = "thank you";
11     printf("%s\n", strcat(s2,s1));
12     printf("%d\n", strcmp(s2, s1));
13
14     printf("%s\n", strcpy(s2, s1));
15     return 0;
16 }


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  strlen strcpy strcat strcmp
相关文章推荐