C 語言字串函式
<string.h> 裡的函式處理字串:strlen 求長度,strcpy 複製,strcat 拼接,strcmp 比較;字串不能用 = 賦值,也不能用 == 比較。
第 13 課我們自己寫迴圈數字串的長度。這種常用的活兒,C 的標準庫早就寫好了,放在 <string.h> 裡。用之前先 #include 它:
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char word[] = "keyboard";6 printf("%s 有 %zu 個字母\n", word, strlen(word));7 return 0;8}
keyboard 有 8 個字母
這一課講四個最常用的:
| 函式 | 做什麼 |
|---|---|
strlen(s) | s 有幾個字元(不算 '\0') |
strcpy(to, from) | 把 from 複製到 to |
strcat(to, from) | 把 from 接到 to 的後面 |
strcmp(a, b) | 比較 a 和 b:一樣是 0 |
用 strlen、strcpy 之前,要 #include 哪個?
strlen、strcpy、strcat、strcmp 都在 <string.h> 裡。<stdio.h> 管 printf 這些輸入輸出,<ctype.h> 管單個字元。strlen 和 sizeof
strlen 數到 '\0' 為止,是文字有多長;sizeof 是陣列有多大。兩個常常不一樣:
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char name[20] = "Maria";6 printf("strlen:%zu\n", strlen(name));7 printf("sizeof:%zu\n", sizeof name);8 printf("漢字:%zu\n", strlen("你好"));9 return 0;10}
strlen:5 sizeof:20 漢字:6
name 有 20 個位元組,只用了 6 個(5 個字母加 '\0')。strlen 數的是位元組:兩個漢字是 6 個位元組,所以顯示 6。
這段程式顯示什麼?
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char s[10] = "abc";6 printf("%zu %zu\n", strlen(s), sizeof s);7 return 0;8}
strlen 數到 '\0' 為止,是 3;sizeof 是整個陣列,聲明瞭 10 個位元組,就是 10。複製:strcpy
陣列不能用 = 整個賦值(第 11 課),字串也一樣。比如這段就編譯不過:
1#include <stdio.h>2 3int main(void) {4 char status[10] = "off";5 status = "on";6 printf("%s\n", status);7 return 0;8}
main.c: In function 'main':
main.c:5:12: error: assignment to expression with array type
5 | status = "on";
| ^assignment to expression with array type 的意思是:不能給陣列賦值。要換掉一個字串的內容,用 strcpy,它把第二個引數裡的字元一個一個複製到第一個引數裡,連 '\0' 一起:
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char status[10] = "off";6 strcpy(status, "on");7 printf("%s\n", status);8 printf("%zu\n", strlen(status));9 return 0;10}
on 2
注意順序:先寫複製到哪裡,再寫從哪裡複製,和 status = "on" 的方向一樣。
strcpy(status①, "on"②);- ①複製到哪裡:這個陣列要放得下
- ②從哪裡複製:連 '\0' 一起復制過去
要把 "cat" 放進 char pet[10];,哪一句對?
= 賦值。strcpy 先寫複製到哪裡,再寫從哪裡複製,所以 pet 在前。拼接:strcat
strcat 找到第一個字串的 '\0',從那裡開始把第二個接上去。常見的做法是先 strcpy 放第一段,再一段一段 strcat:
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char path[30];6 strcpy(path, "photos");7 strcat(path, "/");8 strcat(path, "beach.jpg");9 printf("%s\n", path);10 return 0;11}
photos/beach.jpg
點單步,看 path 的格子一段一段被填上,'\0' 一直往後挪。
這段程式顯示什麼?
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char s[20];6 strcpy(s, "ab");7 strcat(s, "cd");8 strcat(s, "ab");9 printf("%s %zu\n", s, strlen(s));10 return 0;11}
strcat 每次都接在 '\0' 的位置:ab → abcd → abcdab。strlen 不算 '\0',是 6。拼出全名
✓用 strcpy 和 strcat 把 first、一個空格、last 拼進 full,再顯示全名和它的長度:Ada Lovelace(12 個字元)。
Ada Lovelace(12 個字元)
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char first[] = "Ada";6 char last[] = "Lovelace";7 char full[30];8 9 return 0;10}
比較:strcmp
兩個字串一樣不一樣,不能用 == 比:
1#include <stdio.h>2 3int main(void) {4 char saved[] = "secret";5 char typed[] = "secret";6 if (typed == saved) {7 printf("一樣\n");8 } else {9 printf("不一樣\n");10 }11 return 0;12}
不一樣
字都一樣,卻顯示「不一樣」。== 比的不是裡面的字,而是「是不是同一個陣列」;這是兩個陣列,所以永遠不相等(第 17 課講為什麼)。要比字,用 strcmp:兩個一樣就返回 0;第一個排在前面返回負數,排在後面返回正數。
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char saved[] = "secret";6 char typed[] = "secret";7 if (strcmp(typed, saved) == 0) {8 printf("密碼正確\n");9 }10 if (strcmp("apple", "banana") < 0) {11 printf("apple 排在 banana 前面\n");12 }13 return 0;14}
密碼正確 apple 排在 banana 前面
strcmp 從頭一個字元一個字元地比編碼,第一個不一樣的字元決定先後。
哪個排在前面,顯示什麼?
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 if (strcmp("Zoo", "apple") < 0) {6 printf("Zoo\n");7 } else {8 printf("apple\n");9 }10 return 0;11}
'Z' 是 90,'a' 是 97,所以所有大寫字母都排在小寫字母前面,"Zoo" 在前。漢字也是按編碼比,不是按拼音或筆畫。strcmp(a, b) 返回 0,是什麼意思?
strcmp 一個字元一個字元地比,全都一樣才返回 0;a 排在前面返回負數。是不是同一個陣列,它不管。放不下會出事
strcpy 和 strcat 不知道目標陣列有多大,只管往裡寫,寫到 '\0' 為止。目標太小,就寫到陣列外面去了:
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char name[6];6 strcpy(name, "Alexandra");7 printf("%s\n", name);8 return 0;9}
main.c: In function 'main': main.c:6:5: warning: '__builtin_memcpy' writing 10 bytes into a region of size 6 overflows the destination [-Wstringop-overflow=] 6 | strcpy(name, "Alexandra"); | ^~~~~~~~~~~~~~~~~~~~~~~~~ main.c:5:10: note: destination object 'name' of size 6 5 | char name[6]; | ^~~~ buffer overflow
發生了什麼: 停在第 6 行:strcpy:要寫 10 個位元組,可「name」只有 6 個位元組(越界了)。
"Alexandra" 連 '\0' 要 10 個位元組,name 只有 6 個。這叫緩衝區溢位,是 C 程式裡最常見、也最危險的錯之一:多出來的位元組會蓋掉旁邊的資料,壞人還能借它攻擊程式。這一次 gcc 在編譯時就看出來了,輸出最上面那幾行就是它的警告;可警告不會攔住程式,它照樣編譯、執行。我們的引擎在這一行停下來,說清楚要寫幾個位元組、有幾個。點「看看是怎麼出錯的」看一看。
小技巧: 用 strcpy 或 strcat 之前先算一下:結果的 strlen 加 1,不能比陣列的 sizeof 大。
char buf[8] 裡已經是 "Hello",再 strcat(buf, "!!") 行不行?
"Hello!!" 是 7 個字元,加上 '\0' 是 8 個位元組,buf 正好有 8 個。再多接一個字元就溢位了。修好它
✓這段程式越界了,引擎會停下來。把 msg 改大一點,讓它顯示 Hi, Sam。
Hi, Sam
1#include <stdio.h>2#include <string.h>3 4int main(void) {5 char msg[6];6 strcpy(msg, "Hi, ");7 strcat(msg, "Sam");8 printf("%s\n", msg);9 return 0;10}
字元工具:ctype.h
<ctype.h> 裡是處理單個字元的函式。toupper 把小寫字母變成大寫,別的字元原樣返回;tolower 反過來。isdigit 問「是不是數字」,isalpha 問「是不是字母」,是就回傳一個不是 0 的數(真),不是就返回 0:
1#include <stdio.h>2#include <ctype.h>3 4int main(void) {5 char code[] = "ab-42c";6 for (int i = 0; code[i] != '\0'; i++) {7 if (isdigit(code[i])) {8 printf("%c 是數字\n", code[i]);9 } else {10 printf("%c 變成 %c\n", code[i], toupper(code[i]));11 }12 }13 return 0;14}
a 變成 A b 變成 B - 變成 - 4 是數字 2 是數字 c 變成 C
第 13 課我們用 - ('a' - 'A') 自己變大寫;用 toupper 更短,也不用先判斷是不是小寫字母。
這段程式顯示什麼?
1#include <stdio.h>2#include <ctype.h>3 4int main(void) {5 printf("%c%c\n", toupper('q'), toupper('7'));6 return 0;7}
toupper('q') 是 'Q';'7' 不是字母,toupper 原樣返回 '7'。有幾個數字
✓用 isdigit 數一數 text 裡有幾個數字字元,顯示 5 個數字。
5 個數字
1#include <stdio.h>2#include <ctype.h>3 4int main(void) {5 char text[] = "Order 66, room 404";6 7 return 0;8}
這一課學會了
<string.h>:strlen求長度(不算'\0'),strcpy複製,strcat拼接,strcmp比較。strlen是文字的長度,sizeof是陣列的大小;strlen數的是位元組。- 字串不能用
=賦值,要用strcpy;不能用==比較,要用strcmp(a, b) == 0。 strcmp按編碼比:大寫字母排在小寫字母前面。strcpy和strcat不檢查陣列夠不夠大:放不下就是緩衝區溢位。<ctype.h>:toupper、tolower、isdigit、isalpha處理單個字元。