C語言標準庫函數strcpy與strcmp的簡單實現

 1 //C語言標準庫函數strcpy的一種簡單實現。
 2 
 3 //返回值:目標串的地址。
 4 
 5 //對於出現異常的狀況ANSI-C99標準並未定義,故由實現者決定返回值,一般爲NULL。
 6 
 7 //參數:des爲目標字符串,source爲原字符串。
 8 
 9 char* strcpy(char* des,const char* source)
10 {
11     char* r=des;
12  
13     assert((des != NULL) && (source != NULL));
14 
15     while((*des++ = *source++)!='\0');
16 
17     return r;
18 }
19 
20 //while((*des++=*source++));的解釋:賦值表達式返回左操做數,因此在賦值NULL後,循環中止。
 1 //C語言標準庫函數strcmp的一種簡單實現
 2 
 3 //返回值當s1<s2時,返回爲負數;當s1=s2時,返回值= 0;當s1>s2時,返回正數
 4 
 5 //參數:字符串str1,str2
 6 
 7 int strcmp(const char *str1,const char *str2)
 8 {
 9     /*不可用while(*str1++==*str2++)來比較,當不相等時仍會執行一次++,
10     return返回的比較值其實是下一個字符。應將++放到循環體中進行。*/
11     while(*str1 == *str2)
12     {
13         if(*str1 == '\0')
14             return 0;
15          
16         str1++;
17         str2++;
18     }
19     return *str1 - *str2;
20 }
相關文章
相關標籤/搜索