当然!以下是关于【C/C++字符函数和字符串函数】的详细讲解,涵盖常用函数、使用示例及注意事项,帮助你全面掌握字符和字符串的操作。


【C/C++】字符函数和字符串函数详解


目录

  1. 字符函数概述
  2. 常用字符函数列表与用法
  3. 字符串函数概述
  4. 常用字符串函数列表与用法
  5. 字符串操作注意事项
  6. C++ 中的字符串类(std::string)简单介绍
  7. 实战示例

1️⃣ 字符函数概述

字符函数主要用于单个字符的判断和转换,定义在 <ctype.h>(C)或 <cctype>(C++)头文件中。


2️⃣ 常用字符函数及示例

函数功能说明返回值类型示例
isalpha(int c)判断是否字母非0表示是isalpha('A') == true
isdigit(int c)判断是否数字非0表示是isdigit('9') == true
isalnum(int c)判断是否字母或数字非0表示是
isspace(int c)判断是否空白字符(空格、换行等)非0表示是
islower(int c)判断是否小写字母非0表示是
isupper(int c)判断是否大写字母非0表示是
tolower(int c)转换为小写字母转换后字符tolower('A') == 'a'
toupper(int c)转换为大写字母转换后字符toupper('a') == 'A'

示例:

#include <iostream>
#include <cctype>

int main() {
    char ch = 'A';
    if (isalpha(ch)) std::cout << ch << " 是字母\n";
    std::cout << "小写形式: " << (char)tolower(ch) << "\n";
    return 0;
}

3️⃣ 字符串函数概述

字符串函数主要针对以 '\0' 结尾的字符数组(C风格字符串),定义在 <string.h>(C)或 <cstring>(C++)头文件。


4️⃣ 常用字符串函数及示例

函数功能说明返回值类型示例
strlen(const char*)计算字符串长度(不包括 ‘\0’)size_tstrlen("hello") == 5
strcpy(char*, const char*)复制字符串目标字符串指针
strncpy(char*, const char*, size_t)复制指定长度字符串目标字符串指针
strcat(char*, const char*)连接字符串目标字符串指针
strcmp(const char*, const char*)比较两个字符串0相等,>0大于,<0小于strcmp("abc", "abd") < 0
strncmp(const char*, const char*, size_t)比较指定长度字符串同上
strchr(const char*, int)查找字符第一次出现位置指向字符的指针,找不到返回 nullptr
strstr(const char*, const char*)查找子串指向子串起始位置,找不到返回 nullptr
sprintf(char*, const char*, ...)格式化字符串写入字符串长度

示例:

#include <iostream>
#include <cstring>

int main() {
    char str1[20] = "Hello";
    char str2[] = " World";

    strcat(str1, str2);  // 拼接
    std::cout << str1 << "\n";  // 输出 Hello World

    size_t len = strlen(str1);
    std::cout << "长度: " << len << "\n";

    if (strcmp("abc", "abd") < 0) std::cout << "abc < abd\n";

    return 0;
}

5️⃣ 字符串操作注意事项

  • 数组大小:确保目标数组足够大,避免溢出导致安全漏洞。
  • 字符串结尾:C 字符串必须以 '\0' 结束,否则行为未定义。
  • 避免使用 strcpystrcat 等不安全函数,可以用 strncpystrncat 或更安全的替代方案。
  • 避免越界访问,尤其在字符串操作时要特别小心。
  • C++ 推荐使用 std::string,更安全、功能更丰富。

6️⃣ C++ 中的字符串类(std::string)简述

C++ 标准库提供了 std::string 类,简化字符串操作:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "Hello";
    std::string s2 = " World";
    std::string s3 = s1 + s2;
    std::cout << s3 << "\n";  // 输出 Hello World
    std::cout << "长度: " << s3.length() << "\n";
    return 0;
}

std::string 自动管理内存,更安全,支持丰富接口。


7️⃣ 实战示例:统计字符串中数字和字母个数

#include <iostream>
#include <cctype>
#include <cstring>

int main() {
    const char* text = "Hello123! 456";
    int digits = 0, letters = 0;

    for (size_t i = 0; i < strlen(text); ++i) {
        if (isdigit(text[i])) digits++;
        else if (isalpha(text[i])) letters++;
    }

    std::cout << "字母数量: " << letters << "\n";
    std::cout << "数字数量: " << digits << "\n";
    return 0;
}

如需更深入的字符串处理(多字节字符、宽字符、正则表达式、格式化输出)或者更复杂的 C++ 字符串用法(如移动语义、string_view),欢迎告诉我!是否要我帮你写对应的练习题和答案?