字符串,它是多個字符的集合,例如 "abc123"、"123\141\142\143";當然也可以只包含一個字符,例如 "a"、"1"、"\63"。
不過為了使用方便,我們可以用 char 類型來專門表示一個字符,例如:
- char a='1';
- char b='$';
- char c='X';
- char d=' '; // 空格也是一個字符
- char e='\63'; //也可以使用轉義字符的形式
char 稱為字符類型,只能用單引號' '
來包圍,不能用雙引號" "
包圍。而字符串只能用雙引號" "
包圍,不能用單引號' '
包圍。
輸出字符使用 %c,輸出字符串使用 %s。
字符與整數
先看下面一段代碼:
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- char a = 'E';
- char b = 70;
- int c = 71;
- int d = 'H';
- printf("a=%c, a=%d\n", a, a);
- printf("b=%c, b=%d\n", b, b);
- printf("c=%c, c=%d\n", c, c);
- printf("d=%c, d=%d\n", d, d);
- system("pause");
- return 0;
- }
輸出結果:
a=E, a=69
b=F, b=70
c=G, c=71
d=H, d=72
在ASCII碼表中,E、F、G、H 的值分別是 69、70、71、72。
字符和整數沒有本質的區別。可以給 char 變量一個字符,也可以給它一個整數;反過來,可以給 int 變量一個整數,也可以給它一個字符。
char 變量在內存中存儲的是字符對應的 ASCII 碼值。如果以 %c 輸出,會根據 ASCII 碼表轉換成對應的字符;如果以 %d 輸出,那么還是整數。
int 變量在內存中存儲的是整數本身,當以 %c 輸出時,也會根據 ASCII 碼表轉換成對應的字符。
也就是說,ASCII 碼表將整數和字符關聯起來了。不明白的讀者請重溫《ASCII編碼與Unicode編碼》一文,並猛擊這里查看整數與字符的完整對應關系。
字符串
C語言中沒有字符串類型,只能使用間接的方法來表示。可以借助下面的形式將字符串賦值給變量:
char *variableName = "string";
char
和*
是固定的形式,variableNmae 為變量名稱,"string" 是要賦值的字符串。
字符串使用示例:
- #include <stdio.h>
- #include <stdlib.h>
- int main()
- {
- char c = '@';
- char *str = "This is a string.";
- printf("char: %c\n", c);
- printf("string1: %s\n", str);
- //也可以直接輸出字符串
- printf("string2: %s\n", "This is another string.");
- system("pause");
- return 0;
- }
運行結果:
char: @
string1: This is a string.
string2: This is another string.