由於字符串的應用廣泛,為方便用戶對字符串的處理,C語言函數庫中除了前面用到的庫函數gets()與puts()之外,還提供了另外一些常用的庫函數,其函數原型說明在string中。下面介紹一些最常用的字符串庫函數。
1.函數名:strcpy
用法:strcpy(s1,s2)
功能:將s2復制到s1
2.函數名:strcat
用法:strcat(s1,s2)
功能:連接s2到s1的末尾,切s1后面的'\0'被取消
3.函數名:strlen
用法:strlen(s1,s2)
功能:返回s1的長度(不包含空字符)
4.函數名:strcmp
用法:strcmp(s1,s2)
功能:當s1=s2時,返回0值。當s1>s2時,返回大於0的值。當s1<s2時,返回小於0的值。
5.函數名:strchr
用法:strchr(s1,ch)
功能:返回指針,指向ch在s1中的首次出現
6.函數名:strstr
用法:strstr(s1,s2)
功能:返回指針,指向s2在s1中的首次出現
7.函數名:strlwr
用法:strlwr(s)
功能:轉換s中的大寫字母為小寫字母
8.函數名:strupr
用法:strupr(s)
功能:轉換s中的小寫字母為大寫字母
這些函數都是在string函數庫中,所以當用到這些函數的時候都需要聲明頭文件#include <string.h>
下面是示例,由於還沒學到指針章節,所以目前只能理解前面4個函數。
//1.strcpy函數與strcat函數 #include <stdio.h> #include <string.h> int main() { char buffer[80]; //buffer數組作為緩沖數組。 strcpy(buffer,"hello"); //把“hello”復制給buffer數組。 strcat(buffer," world!"); //把“ world”連接到buffer數組的后面。 printf("%s",buffer); }
//2.strlen函數與strcmp函數 #include <stdio.h> #include <string.h> int main() { char buf1[]="aaa",buf2[]="bbb",buf3[]="ccc"; int buf; printf("buf1的長度為:%d\n",strlen(buf1)); buf=strcmp(buf1,buf2); if(buf>0) printf("buf1 is greate than buf2.\n"); else printf("buf1 is less than buf2.\n"); buf=strcmp(buf2,buf3); if(buf>0) printf("buf2 is greate than buf3.\n"); else printf("buf2 is less than buf3\n"); }