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

 

一定义:

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

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

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

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

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

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

char ch1[]={ 'c', '+', '+'};//不是C风格字符串
char ch2[]={ 'c', '+', '+', ''};//C风格字符串
char ch3[] = "C++";//C风格字符串
sizeof(ch3) = 4;
strlen(ch3) = 3;

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

strlen(s) : 返回S的长度,不包括字符串结束符NULL;
strcmp(s1,s2) :比较两个字符串是否相同,若s1==s2,返回0,若s1>s2则返回正数,若s1<s2则返回负数;
strcat(s1,s2):将字符串s2连接到s1上,返回 s1;
strcpy(s1,s2):将s2,复制到s1,返回 s1.

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

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

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

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++ != '') //2'
 8         count++;
 9     return count;//3'
10 }
View Code

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 != '')//走到末尾
 7         strD ++;
 8 
 9     while(*strD++ = *strS++);//cat
10     return address; //attention
11 } 
View Code

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 }
View Code

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为’‘,则其先赋值给strD,故最后不需要再添加''
 7     while(*strD++ = *strS++);
 8 
 9     return address;
10 }
View Code

测试函数如下:

 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
", s1);
 9     
10     char s2[100] = "thank you";
11     printf("%s
", strcat(s2,s1));
12     printf("%d
", strcmp(s2, s1)); 
13 
14     printf("%s
", strcpy(s2, s1));
15     return 0;
16 }
View Code
原文地址:https://www.cnblogs.com/xfxu/p/4083652.html