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

C 語言字符串操作完全指南:核心函數實戰與字符分類詳解

     編輯:關於C語言

核心字符串函數實戰(示例一)

#include <stdio.h> #include <string.h>

void display(const char* name, const char* str) {
    printf("%s%s\n", name, str);
}

int main() {
    char ch1[40] = "hello world";
    char ch2[40] = "I love you";
    
    display("ch1= ", ch1);
    display("ch2= ", ch2);
    
    // 1. 長度
    printf("len= %zu\n", strlen(ch1));
    
    // 2. 比較
    printf("strcmp= %d\n", strcmp(ch1, ch2));
    
    // 3. 字符查找 → 返回子串指針
    display("strchr 'w': ", strchr(ch1, 'w'));
    
    // 4. 子串查找
    display("strstr 'world': ", strstr(ch1, "world"));
    
    // 5. 字符集查找(首個匹配字符)
    display("strpbrk 'l': ", strpbrk(ch1, "l"));
    
    // 6. 字符集前綴長度
    printf("strspn 'he': %zu\n", strspn(ch1, "he"));
    
    // 7. 追加
    strcat(ch1, ch2);
    display("strcat: ", ch1);
    
    // 8. 複製
    strcpy(ch1, ch2);
    display("strcpy: ", ch1);
    
    return 0;
}

關鍵函數行為速查

函數返回值注意事項
strlensize_t 長度不含結束符 \0
strcmp<0 / 0 / >0字典序比較
strchrchar* 指針未找到返回 NULL
strstrchar* 指針子串首次出現位置
strcatdest 指針需保證 dest 空間足夠
strcpydest 指針含 \0 複製,有溢出風險

字符串↔數值轉換(示例二)

#include <stdlib.h>
char num[] = "4.56";
int    i = atoi(num);   // 4
float  f = atof(num);   // 4.56
double d = atof(num);   // 4.56
// 更安全的現代替代:strtol/strtod 族函數

字符分類函數(<ctype.h>)

函數判斷條件示例
isalpha字母 A-Z/a-zisalpha('a')=真
isupper / islower大寫 / 小寫字母isupper('A')=真
isdigit十進制數字 0-9isdigit('5')=真
isxdigit十六進制字符 0-9/A-F/a-fisxdigit('F')=真
isspace空白字符(空格/換行/製表)isspace(' ')=真
iscntrl控制字符iscntrl('\r')=真
ispunct標點符號ispunct(',')=真
isalnum字母或數字isalnum('4')=真
isprint可打印字符(含空格)isprint('d')=真
isgraph可見字符(非空格)等價 isalnum|ispunct

安全編程提醒

  • 避免 strcpy/strcat/sprintf,改用 strncpy/strncat/snprintf 或 C++ std::string
  • 字符分類函數參數需轉 unsigned char 避免負值未定義行為
  • 區域設置(locale)影響字符分類結果,跨平台注意

掌握以上核心函數與分類邏輯,覆蓋 90%+ 字符串處理場景。

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