字符與字符串是程序處理文本的基石。C 語言以 char 類型為核心,配合 ASCII 編碼,構建了極簡卻強大的文本處理模型。本文從存儲本質、輸入輸出、常見操作三個維度建立完整認知。
char 是整數類型(通常 1 字節),存儲的是編碼值而非圖形符號。'A'=65、'Z'=90、'a'=97、'z'=122、'0'=48、空格=32。#include <stdio.h>
int main(void) {
char c1 = 'A';
char c2 = 65; // 直接賦 ASCII 值
printf("字符: %c, ASCII: %d\n", c1, c1); // 字符: A, ASCII: 65
printf("字符: %c, ASCII: %d\n", c2, c2); // 字符: A, ASCII: 65
// 遍歷可打印字符
for (int i = 32; i < 127; ++i) {
printf("%3d: %c ", i, i);
if ((i - 31) % 8 == 0) putchar('\n');
}
return 0;
}
| 聲明方式 | 內存模型 | 可修改性 | 生命週期 |
|---|---|---|---|
char *s = "hello"; | 指向只讀數據段 | 不可修改(UB) | 程序全期 |
char s[] = "hello"; | 棧上數組,內容為拷貝 | 可修改 | 作用域結束 |
char *s = malloc(6); strcpy(s, "hello"); | 堆內存 | 可修改 | 手動 free |
| 函數 | 用途 | 備註 |
|---|---|---|
strlen | 長度(不含 \0) | O(n),勿放在循環條件中重複調用 |
strcpy/strncpy | 拷貝 | strncpy 不保證以 \0 結尾,需手動補 |
strcat/strncat | 拼接 | 目標空間需足夠 |
strcmp/strncmp | 比較 | 返回 <0, 0, >0 |
strchr/strrchr | 查找字符 | 返回指針或 NULL |
strstr | 查找子串 | 返回指針或 NULL |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void) {
char line[1024];
puts("請輸入文本 (空行結束):");
while (fgets(line, sizeof(line), stdin)) {
if (line[0] == '\n') break; // 空行退出
int letters = 0, digits = 0, spaces = 0, others = 0;
for (size_t i = 0; line[i] && line[i] != '\n'; ++i) {
unsigned char uc = line[i];
if (isalpha(uc)) letters++;
else if (isdigit(uc)) digits++;
else if (isspace(uc)) spaces++;
else others++;
}
printf("字母:%d 數字:%d 空格:%d 其他:%d\n", letters, digits, spaces, others);
}
return 0;
}
理解字符即整數、字符串即以 \0 結尾的字符數組、輸入必須檢查邊界,這三個核心認知將讓你在 C 語言文本處理中游刃有餘。