C語言簡介:字串

本文為C語言簡介系列第六篇文章,前一篇文章為C語言簡介:陣列

其實我們可以把字串看作一個字元(char)陣列

宣告

如同上面所說,我們可以把字串看做一個字元陣列!
所以字串的宣告跟陣列的宣告很像:

char s[11] = "HelloWorld";

數一數會發現

字元 H e l l o W o r l d
字元個數 1 2 3 4 5 6 7 8 9 10

明明只有10個字元欸?為何要宣告長度為11的陣列?
這是因為字串的最後會再加上一個 \0

字元 H e l l o W o r l d \0
字元個數 1 2 3 4 5 6 7 8 9 10 11

標頭檔

在今天開始使用字串相關的函數前,請大家先在程式碼最上方加上

#include <string.h>

因為 strlen()strcpy() 等字串相關函數並不在 stdio.h 裡面!
今天只跟大家簡要說明幾個函數,因為 string.h 裡的函數其實不少!有興趣的讀者可以自行上網搜尋。

函數

strlen()

這個函數可以讓我們取得字串長度。

使用示例

程式範例

strlen_example.c
1
2
3
4
5
6
7
8
9
#include <string.h>
#include <stdio.h>
int main() {
char str[] = "Welcome to wmcs.dev";
int n = 0;
n = strlen(str);
printf("%d", n);
return 0;
}

輸出

19

strcpy()

此函數用以將字串複製到另一字串。
使用方法為
strcpy(dest, src):將 src 字串複製至 dest 字串。

註:dest 之陣列長度應 >= strlen(src) + 1(因為還有 \0)。

使用示例

程式範例

strcpy_example.c
1
2
3
4
5
6
7
8
9
#include <string.h>
#include <stdio.h>
int main() {
char s1[] = "This is S1";
char s2[15];
strcpy(s2, s1);
printf("%s", s2);
return 0;
}

輸出

This is S1

strcat()

此函數用以將字串串接到另一字串尾端。
使用方法為
strcat(str1, str2):將 str2 字串接到 str1 後。

註:str1 之陣列長度應 >= strlen(str1) + strlen(str2) + 1(因為還有 \0)。

使用示例

程式範例

strcat_example.c
1
2
3
4
5
6
7
8
9
#include <string.h>
#include <stdio.h>
int main() {
char s1[50] = "Welcome to";
char s2[25] = " wmcs.dev";
strcat(s1, s2);
printf("%s", s1);
return 0;
}

輸出

Welcome to wmcs.dev

strcmp()

此函數用以比較兩字串。
使用方法為
strcmp(str1, str2):比較 str1str2
若return值 > 0:前者字典序較後
若return值 < 0:前者字典序較前
若return值 = 0:兩者相等

使用示例

程式範例

strcmp_example.c
1
2
3
4
5
6
7
8
9
10
#include <string.h>
#include <stdio.h>
int main() {
char s1[50] = "abcdefg";
char s2[25] = "acegi";
int n = 0;
n = strcmp(s1, s2);
printf("%d", n);
return 0;
}

輸出

-1

註:實際數值依實作而定,本例可能輸出 -1。

結語

以上就是C語言字串簡介。
倘內容有誤或仍有疑問,歡迎在下方留言區留言!