C字符串——庫函數系列(strlen、strcat、strcpy、strcmp)


 

一定義:

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

子串:字符串中任意個連續的字符組成的子序列,並規定空串是任意串的子串,字符串本身也是子串之一;“abcdefg”,”abc“就是其子串,但是“ade”不屬於子串范圍。

子序列:不要求字符連續,但是其順序與其在主串中相一致;上例中,“abc”與“ade”都屬於子序列范圍;

二:C風格字符串包括兩種:

1)字符串常量---以雙引號括起來的字符序列,編譯器自動在其末尾添加一個空字符

2)末尾添加了’0‘的字符數組;

char ch1[]={ 'c', '+', '+'};//不是C風格字符串
char ch2[]={ 'c', '+', '+', '\0'};//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、要自行添加字符串的結束符‘\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 }
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 != '\0')//走到末尾
 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為’\0‘,則其先賦值給strD,故最后不需要再添加'\0'
 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\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 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM