乐闻世界logo
搜索文章和话题

C语言中字符串处理函数的完整列表和最佳实践是什么?

2月18日 17:21

C语言中字符串处理函数的完整列表和最佳实践是什么?

核心字符串函数:

  1. 字符串长度

    c
    size_t strlen(const char *str); // 返回字符串长度,不包含终止符 '\0'
  2. 字符串复制

    c
    char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); // strncpy 不会自动添加 '\0',需要手动处理
  3. 字符串连接

    c
    char *strcat(char *dest, const char *src); char *strncat(char *dest, const char *src, size_t n); // 确保目标缓冲区足够大
  4. 字符串比较

    c
    int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); // 返回值:0表示相等,<0表示s1<s2,>0表示s1>s2
  5. 字符串查找

    c
    char *strchr(const char *str, int c); // 查找字符首次出现 char *strrchr(const char *str, int c); // 查找字符最后出现 char *strstr(const char *haystack, const char *needle); // 查找子串
  6. 字符串分割

    c
    char *strtok(char *str, const char *delim); // 注意:strtok 会修改原字符串,且不是线程安全的
  7. 安全版本(C11)

    c
    errno_t strcpy_s(char *dest, rsize_t destsz, const char *src); errno_t strcat_s(char *dest, rsize_t destsz, const char *src);

最佳实践:

  1. 缓冲区溢出防护

    c
    // 不安全 strcpy(dest, src); // 安全方式 strncpy(dest, src, sizeof(dest) - 1); dest[sizeof(dest) - 1] = '\0';
  2. 字符串拼接安全

    c
    char buffer[100]; snprintf(buffer, sizeof(buffer), "%s%s", str1, str2);
  3. 动态字符串处理

    c
    char *safe_strdup(const char *str) { if (!str) return NULL; size_t len = strlen(str) + 1; char *copy = malloc(len); if (copy) memcpy(copy, str, len); return copy; }
  4. 字符串格式化

    c
    char buffer[256]; int result = snprintf(buffer, sizeof(buffer), "Value: %d", value); if (result < 0 || result >= sizeof(buffer)) { // 处理错误 }

常见陷阱:

  • 忘记为 '\0' 预留空间
  • 使用未初始化的字符串
  • 混淆 strlen 和 sizeof
  • 忽略函数返回值
  • 多次调用 strtok 时的状态问题
标签:C语言