C 語言 講義  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 A B C

常用內建函數

字串處理函數

拷貝字串
[函數名稱] [語法]                                 [說明]
[strcpy  ] [strcpy(char *s1, char *s2);         ] [將字串 s2 拷貝到 s1]
[strncpy ] [strncpy(char *s1, char *s2, int n); ] [將字串 s2 最多 n 個字元拷貝到 s1]

字串相接
[函數名稱] [語法]                                 [說明]
[strcat  ] [strcat(char *s1, char *s2);         ] [將字串 s2 接到 s1 的尾端 ]
[strncat ] [strncat(char *s1, char *s2, int n); ] [將字串 s2 最多 n 個字元接到 s1 的尾端 ]

計算字串的長度
[函數名稱] [語法]                      [說明]
[strlen  ] [int n = strlen(char *s); ] [計算字串s的長度 ]

例子:-------------------------------------------------------------------------------------
#include
#include
void main()
{
 char s1[101],s2[101];
 // s1 = "Hello";    是錯誤的寫法
 strcpy(s1,"Hello"); //正確的寫法
 strncpy(s2,"This is a book.",4);
 printf("s1: [%s], s2: [%s]\n",s1,s2); //輸出 s1: [Hello], s2: [This]
 strcat(s1,", Tom.");
 strncat(s2," is a book about C language.",10);
 printf("s1: [%s], s2: [%s]\n",s1,s2); //輸出 s1: [Hello, Tom.], s2: [This is a book]
 int i1=strlen(s1), i2=strlen(s2);
 printf("length of s1:%d, length of s2:%d\n",i1,i2); //輸出 length of s1:11, length of s2:15
}//---------------------------------------------------------------------------------------


判斷兩個字串是否相等
[函數名稱] [語法]                                        [說明]
[strcmp  ] [int r = strcmp(char *s1, char *s2);        ] [判斷s1 與 s2 兩個字串是否相等 ]
[strncmp ] [int r = strncmp(char *s1, char *s2,int n); ] [判斷s1 與 s2 兩個字串前 n 個字元是否相等 ]
[傳回值 <0,s1小於s2
 傳回值 >0,s1大於s2
 傳回值 =0,s1相等s2 ]

字串的搜尋處理
[函數名稱] [語法]                                 [說明]
[strchr  ] [char *p=*strchr(char *s1, int c);   ] [字串 s1 中,字元 c 第一次出現位置的指標 ]
[strrchr ] [char *p=*strchr(char *s1, int c);   ] [字串 s1 中,字元 c 最後一次出現位置的指標 ]
[strstr  ] [char *p=*strstr(char *s1, char *s2);] [字串 s1 中, 字串 s2第一次出現位置的指標 ]

例子:-------------------------------------------------------------------------------------
#include
#include
void main()
{
 char s1[101],s2[101], *ptr;
 strcpy(s1,"This is a dog.");
 strcpy(s2,"This is a book.");
 int b1=strcmp(s1,s2), b2=strcmp(s2,s1), b3=strncmp(s1,s2,8);
 printf("b1:%d, b2:%d, b3:%d\n",b1,b2,b3); //輸出 b1:2, b2:-2, b3:0
 ptr=strchr(s1,'s');
 printf("pointer of s1:%d, ptr:%d\n",s1,ptr,ptr-s1); //輸出 pointer of s1:-13424, ptr:-13421
 printf("location(from 0):%d\n",ptr-s1); //輸出 location(from 0):3
 ptr=strrchr(s1,'s');
 printf("location(from 0):%d\n",ptr-s1); //輸出 location(from 0):6
 ptr=strstr(s1,"is");
 printf("location(from 0):%d\n",ptr-s1); //輸出 location(from 0):2
} // -------------------------------------------------------------------------------------


數學函數



[函數名稱] [語法]                                 [說明]
[  ] [ ] [ ]
[ ] [ ] [ ]