c語言字串處理的常用庫函式總結

2021-07-24 21:03:41 字數 2785 閱讀 4783

對c語言的字串處理的常用庫函式總結一下,並進行實現。

1. 字串比較

1. 字串比較:

int strcmp(consyt char *s1,const char *s2);

比較兩個字串的大小(不忽略大小寫),是以ascii碼表上順序來比較的,strcmp()首先將s1第乙個字元值減去s2,第乙個字元值,若差值為0,則再比較下乙個字元,若差值不為0,則將差值返回。

實現如下:

字串比較:

int strcmp(consyt char *s1,const char *s2);

比較兩個字串的大小(不忽略大小寫),是以ascii碼表上順序來比較的,strcmp()首先將s1第乙個字元值減去s2,第乙個字元值,若差值為0,則再比較下乙個字元,若差值不為0,則將差值返回。

int my_strcmp(const char *s1,const char *s2)

if (null == s1 && null == s2)

printf("my_strcmp() err\n");

while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)

s1++;

s2++;

return *s1 - *s2;

注:while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)

*s1 != '\0'等價於 *s1

測試:char *str1 = "abcd";

char *str2 = "abae";

printf("my_strcmp(str1,str2):%d \n",my_strcmp(str1,str2));

1. 字串n比較

strcmp是常用的字串比較函式,一般用法是if(!strcmp(s1,s2)){}.如果不是對z整個字串進行比較而只是比較指定數目的字串,可以使用函式:

int strncmp(const char* s1,const *s2,size_t n);

比較給定字串的前n個字元,或者遇到任一字串結尾

實現如下

int my_strncmp(const char *s1,const char *s2,size_t n)

if (null == s1 || null == s2 || n < 0)

printf("my_strncmp() err\n");

int num = 1;

while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2 && num < n)

s1++;

s2++;

num++;

return *s1 - *s2;

測試:printf("my_strncmp(str1,str2):%d \n",my_strncmp(str1,str2,4));

2. 字串查詢:

cahr * strchr(const char *s,int c)

函式返回在s中找到第乙個c的位置指標,注意的是,字串末尾的』\0』也是可以被查詢到的。

實現1:

char * my_strchr(char *s,int c)

if (null == s)

printf("my_strchr() err\n");

while (*s != '\0' && *s != c)

++s;

return *s == c ? s:null;

或者直接把int c換成char c

char * my_strchr2(char *s,char c)

if (null == s)

printf("my_strchr() err\n");

while (*s != '\0' && *s != c)

++s;

return *s == c ? s:null;

測試:printf("strchr:%s\n",my_strchr2(str1,'b'));

3. strstr:查詢字串函式

char *strstr(const char s1,const char *s2)

函式返回s2在s1中出現的首字元的位置

const char *my_strstr(const char *s1,const char *s2)

if (null == s1 && null == s2)

printf("my_strstr() err\n");

while(*s1 != '\0')

const char *p = s1;

const char *q = s2;

const char *res = null;

if(*p == *q)

res = p;

while(*p && *q && *p++ == *q++)

if(*q == '\0')

return res;

s1++;

return null;

測試:printf("my_strstr(str1,str2):%s \n",my_strstr(str1,str2));

4. 字串複製

strcpy: char *strcpy(char *dst,const char *src);

把src所指向的由null結尾的字串複製到由dst所指向的字串中

char *my_strcpy(char *dst,const char *src)

char *s = dst;

while (*dst++ = *src++)

return s;

C語言的字串常用庫函式

strcpy str1,str2 將字串str2複製到str1中,這個庫函式不會檢查str1的容量是否足夠長度。strncpy str1,str2,size t 將字串str2從頭開始複製size t個字元到str1中,這個庫函式會檢查str1的容量是否足夠長度。memset str,0 5 將st...

C語言字串操作常用庫函式

函式名 strrchr 功 能 在串中查詢指定字元的最後乙個出現 用 法 char strrchr char str,char c 舉例 char fullname lib lib1.so char ptr ptr strrchr fullname,printf filename is s ptr ...

C語言字串常用庫函式手冊

strcpy char strcpy char strdestination,const char strsource strcpy 函式將 strsource 包括終止空字元 複製到 strdestination 指定的位置。返回值為目標字串。由於 strcpy 不會在複製 strsource 前...