strcpy、strncpy、strcmp、strncmp、strlen源碼

來源:互聯網
上載者:User

標籤:

strcpy
#include <string.h>
#include <assert.h>
char * strcpy( char *strDest, const char *strSrc )//將源字串加const,表明其為輸入參數
{
assert( (strDest != NULL) &&(strSrc != NULL) ); //對源地址和目的地址加非0斷言,檢查指標的有效性
char *str = strDest;
while( (*strDest++ = * strSrc++) != ‘\0‘ );//迴圈體結束後,strDest字串的末尾正確地加上‘\0‘
return str; //為了實現鏈式操作,將目標地址返回
}

strncpy

#include <string.h>
char * strncpy (char * dest,const char * source,int count)
{
char *start = dest;
while (count && (*dest++ =*source++)) /* copy string */
count--;
if (count) /* pad out with zeroes */
while (--count)
*dest++ = ‘\0‘;
return(start);
}

strcmp

#include <string.h>
int strcmp(const char *str1,const char *str2)
{
/*不可用while(*str1++==*str2++)來比較,當不相等時仍會執行一次++,
return返回的比較值實際上是下一個字元。應將++放到迴圈體中進行。*/
while(*str1 == *str2)
{
if(*str1 == ‘\0‘)
return0;
str1++;
str2++;
}
return *str1 - *str2;
}

strncmp
//不區分大小寫
int strncmp(const char * s1, const char * s2, size_t len)
{
while(len--) {
if(*s1 == 0 || *s1 != *s2)
return *s1 - *s2;
s1++;
s2++;
}
return 0;
}
//區分大小寫
#include <ctype.h>
int strnicmp(const char * s1, const char * s2, size_t len)
{
register signed char r;
while(len--) {
if((r = toupper(*s1) - toupper(*s2)) || *s1 == 0)
return r;
s1++;
s2++;
}
return 0;
}

strlen

size_t strlen_a(const char *str) {
size_t length = 0;
while (*str++)
++length;
return length;
}
size_t strlen_b(const char *str) {
const char *cp = str;
while (*cp++);
return (cp - str - 1);
}

 

strcpy、strncpy、strcmp、strncmp、strlen源碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.