# 字串(string) ## 什麼是字串📖 簡單來說,C語言的字串就是一個字元(char)的陣列,並在結尾的地方加上一個\0 (NULL) ## 用法 ### 宣告模式 兩種方法 第一種:`char string[7] = {'s','t','r','i','n','g','\0'};` 第二種:`char string[7] = "string"` ### 注意❗ 因為會多出一個 `\0` 所以設定陣列大小記得+1 ### 字串的輸入 使用 scanf 取得字串時,格式指定字是使用 %s,變數前面也不用再加上 & ,因為字串(字元陣列) 變數名稱即表示為記憶體的位置 ### 示範Code👉 ```c #include <stdio.h> int main() { char yourName[80] = "noInput"; int yourAge = 0; printf("Please enter your name and age : Ex.ruserxd 19\n"); scanf("%s %d", yourName, &yourAge); printf("\n%s %d", yourName, yourAge); return 0; } ``` --- # 應用string.h ## 什麼是string.h📖 C語言中一個標頭檔,專門用來處理字串,讓程式更好懂、更精簡 ## 注意❗ 在 C 寫字串時,請注意溢位問題(陣列開的大小) ## strlen - 用途 `size_t strlen(const char *str)` 計算一個str的長度,但不包括`\0` - 示範Code👉 ```c #include <stdio.h> #include <string.h> int main() { char string[80] = "HowLong"; printf("%lu", strlen(string)); return 0; } ``` <div style="width: 400px; height: 120px; background: #ECF5FF;padding: 1em;"> sizeof跟strlen的差別💡 sizeof是用來計算變數或類別所占用的記憶體 strlen用於計算字串的char數量,不包括('\0') </div> ## strcpy - 用途 `char *strcpy(char *dest, const char *src)` 會把 dest 的字串複製成 src 的字串 - 示範Code👉 ```c #include <stdio.h> #include <string.h> int main() { char string[80],temp_string[80]; strcpy(string,"Hello"); printf("%s\n",string); strcpy(temp_string," ,World!"); printf("%s\n",temp_string); } ``` ## strcat - 用途 `char *strcat(char *dest, const char *src)` 將src 複製到 dest 結尾符號的後方 簡單來說就是將兩個字串合併起來 - 示範Code👉 ```c #include <stdio.h> #include <string.h> int main() { char string[80],temp_string[80]; strcpy(string,"Hello"); printf("%s\n",string); strcpy(temp_string," ,World!"); printf("%s\n",temp_string); strcat(string,temp_string); printf("%s",string); } ``` ## strcmp - 用途 `int strcmp(const char *str1, const char *str2)` str1 跟 str2 為要比較的字串 (按照ASCII比較) 兩個字串相同,回傳0 (st1 > str2) 回傳 > 0 的數字 (st1 < str2) 回傳 < 0 的數字 - 示範Code👉 ```c #include <stdio.h> #include <string.h> //A simple password system int main() { char yourPassword[10] = "chupie666"; char userInput[80]; while (1) { printf("Please enter password: "); scanf("%s", userInput); if (strcmp(yourPassword, userInput) == 0) { printf("Welcome to ruserSystme!\n"); break; } else { printf("Not correct.\n"); printf("Please try again.\n"); } } } ``` ## CPE課堂練習 [Summing Digits](https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=25&page=show_problem&problem=2307) [FCU](https://oj.fcu.edu.tw/contest/846) password:chipie ## leetcode 課堂練習 [344. Reverse String](https://leetcode.com/problems/reverse-string/) ## 參考 [字元陣列與陣列](https://openhome.cc/Gossip/CGossip/String.html) [字串](https://mycollegenotebook.medium.com/c-%E8%AA%9E%E8%A8%80%E7%AD%86%E8%A8%98-%E5%AD%97%E4%B8%B2-strings-ffe70ee5f5b8) [string.h](https://www.runoob.com/cprogramming/c-standard-library-string-h.html) [w3schools](https://www.w3schools.com/c/c_strings.php)