首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言字串操作完全指南:標準庫函式、寬字元、安全替代方案

     編輯:關於C語言

標準字串函式速查表 (<string.h>)

函式功能安全版本 (C11 Annex K)
strcpy(dest, src)複製字串strcpy_s(dest, destsz, src)
strncpy(dest, src, n)複製前 n 字符strncpy_s(dest, destsz, src, n)
strcat(dest, src)拼接字串strcat_s(dest, destsz, src)
strncat(dest, src, n)拼接前 n 字符strncat_s(dest, destsz, src, n)
strlen(str)字串長度 (不含 \0)-
strcmp(s1, s2)比較字串 (字典序)-
strncmp(s1, s2, n)比較前 n 字符-
strchr(s, c)查找字符首次出現-
strrchr(s, c)查找字符最後出現-
strstr(s1, s2)查找子串首次出現-
strtok(s, delim)分割字串 (破壞原串、非線程安全)strtok_s

輸入函式對比

函式標準緩衝區保護保留換行適用流
gets(buf)C89 (C11 移除)無 (極危險)否stdin
fgets(buf, n, fp)C89有 (指定 n)是任意 FILE*
gets_s(buf, n)C11有否stdin

建議:永遠使用 fgets 或 gets_s,棄用 gets。

數值轉換函式 (<stdlib.h>)

double atof(const char *str);   // 字串轉 double
int    atoi(const char *str);   // 字串轉 int
long   atol(const char *str);   // 字串轉 long
long long atoll(const char *str); // 字串轉 long long (C99)

// 更健壯的替代:strtod, strtol, strtoul, strtoll
// 提供錯誤檢測、進制支援、末尾指標回傳

寬字元字串 (<wchar.h>)

支援 Unicode (UTF-16/UTF-32 視平台),前綴 L:

wchar_t *ws = L"寬字元字串";
wprintf(L"%ls\n", ws);           // %ls 輸出寬字串
wcslen(ws);                      // 長度
wcscpy(dest, src);               // 複製
wcsncpy(dest, src, n);           // 複製 n 字符
wcscat(dest, src);               // 拼接
wcscmp(s1, s2);                  // 比較
wcschr(ws, L'中');               // 查找寬字符
wcsstr(ws, L"字串");             // 查找寬子串
fgetws(buf, n, stdin);           // 安全讀入寬字串

完整示範程式

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>  // setlocale

int main() {
    setlocale(LC_ALL, "");  // 支援本地化字符

    // 窄字串操作
    char s1[50] = "Hello";
    char s2[] = " World";
    strcat(s1, s2);
    printf("拼接: %s (長度: %zu)\n", s1, strlen(s1));

    // 安全輸入
    char buf[100];
    printf("輸入一行: ");
    fgets(buf, sizeof(buf), stdin);
    buf[strcspn(buf, "\n")] = '\0';  // 移除換行
    printf("你輸入: %s\n", buf);

    // 數值轉換
    char num[] = "3.14159";
    double val = atof(num);
    printf("atof: %.5f\n", val);

    // 寬字串
    wchar_t ws1[50] = L"寬字元";
    wchar_t ws2[] = L"測試";
    wcscat(ws1, ws2);
    wprintf(L"寬字串拼接: %ls (長度: %zu)\n", ws1, wcslen(ws1));

    // 寬字串輸入
    wchar_t wbuf[100];
    fgetws(wbuf, 100, stdin);
    wprintf(L"寬字串輸入: %ls", wbuf);

    return 0;
}

常見坑與最佳實踐

  • 緩衝區溢位:永遠指定目標緩衝區大小,用 snprintf, strncat_s, fgets
  • 字串字面量唯讀:char *p = "abc"; p[0] = 'x'; // UB,用 char arr[] = "abc";
  • 字串結束符:strncpy 若源長 ≥ n,**不自動加 \0**,需手動補齊
  • locale 影響:strcoll, wcscoll 依賴 LC_COLLATE
  • 多線程:strtok 非線程安全,用 strtok_r (POSIX) 或 strtok_s (C11)

總結

C 語言字串操作核心在於「手動管理緩衝區、以 \0 結尾、指標運算」。掌握標準庫函式語義、安全版本替代、寬字元支援、輸入輸出最佳實踐,能寫出健壯、可移植、無安全漏洞的字串處理代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved