常用字符串处理函数

文本处理工具库

C语言提供了丰富的字符串处理函数,用于文本数据的各种操作。东巴文(db-w.cn) 将带你深入学习这些函数,掌握文本处理的核心技能。

💡 东巴文观点:字符串处理函数是C语言文本处理的利器,熟练掌握它们可以大大提高开发效率。

字符串处理函数概述

字符串函数分类

东巴文说明:C语言字符串函数主要分为以下几类:

字符串函数分类
├── 长度与复制
│   ├── strlen - 字符串长度
│   ├── strcpy - 字符串复制
│   └── strncpy - 安全复制
├── 连接与比较
│   ├── strcat - 字符串连接
│   ├── strncat - 安全连接
│   ├── strcmp - 字符串比较
│   └── strncmp - 部分比较
├── 查找与定位
│   ├── strchr - 查找字符
│   ├── strrchr - 反向查找字符
│   ├── strstr - 查找子字符串
│   └── strtok - 字符串分割
└── 转换与处理
    ├── atoi - 字符串转整数
    ├── atof - 字符串转浮点数
    ├── tolower - 转小写
    └── toupper - 转大写

字符串长度与复制

strlen - 字符串长度

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

int main() {
    printf("=== 东巴文strlen函数 ===\n\n");
    
    char str[] = "Hello, 东巴文";
    
    // strlen: 返回字符串长度(不包括'\0')
    size_t len = strlen(str);
    
    printf("字符串:%s\n", str);
    printf("strlen: %zu\n", len);
    printf("sizeof: %zu\n", sizeof(str));
    
    return 0;
}

东巴文说明

  • strlen 返回字符串长度,不包括 \0
  • sizeof 返回数组大小,包括 \0

strcpy - 字符串复制

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

int main() {
    printf("=== 东巴文strcpy函数 ===\n\n");
    
    char src[] = "东巴文欢迎您";
    char dest[50];
    
    // strcpy: 复制字符串
    strcpy(dest, src);
    
    printf("源字符串:%s\n", src);
    printf("目标字符串:%s\n", dest);
    
    return 0;
}

东巴文说明

  • strcpy 会复制整个字符串,包括 \0
  • 目标数组必须足够大
  • 返回目标字符串的指针

strncpy - 安全复制

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

int main() {
    printf("=== 东巴文strncpy函数 ===\n\n");
    
    char src[] = "东巴文欢迎您";
    char dest[10];
    
    // strncpy: 复制指定长度的字符串
    strncpy(dest, src, sizeof(dest) - 1);
    dest[sizeof(dest) - 1] = '\0';  // 确保以'\0'结尾
    
    printf("源字符串:%s\n", src);
    printf("目标字符串:%s\n", dest);
    
    return 0;
}

东巴文说明

  • strncpy 更安全,可以限制复制长度
  • 如果源字符串长度超过指定长度,不会自动添加 \0
  • 建议手动添加 \0

字符串连接与比较

strcat - 字符串连接

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

int main() {
    printf("=== 东巴文strcat函数 ===\n\n");
    
    char str1[50] = "东巴文";
    char str2[] = " 欢迎您";
    
    // strcat: 连接字符串
    strcat(str1, str2);
    
    printf("连接后:%s\n", str1);
    
    return 0;
}

东巴文说明

  • strcat 将源字符串连接到目标字符串末尾
  • 目标数组必须足够大
  • 返回目标字符串的指针

strncat - 安全连接

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

int main() {
    printf("=== 东巴文strncat函数 ===\n\n");
    
    char str1[20] = "东巴文";
    char str2[] = " 欢迎您来到C语言世界";
    
    // strncat: 连接指定长度的字符串
    strncat(str1, str2, sizeof(str1) - strlen(str1) - 1);
    
    printf("连接后:%s\n", str1);
    
    return 0;
}

东巴文说明

  • strncat 更安全,可以限制连接长度
  • 会自动添加 \0

strcmp - 字符串比较

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

int main() {
    printf("=== 东巴文strcmp函数 ===\n\n");
    
    char str1[] = "apple";
    char str2[] = "banana";
    char str3[] = "apple";
    
    // strcmp: 比较字符串
    int result1 = strcmp(str1, str2);
    int result2 = strcmp(str1, str3);
    int result3 = strcmp(str2, str1);
    
    printf("strcmp(\"%s\", \"%s\") = %d\n", str1, str2, result1);
    printf("strcmp(\"%s\", \"%s\") = %d\n", str1, str3, result2);
    printf("strcmp(\"%s\", \"%s\") = %d\n", str2, str1, result3);
    
    if (strcmp(str1, str3) == 0) {
        printf("\"%s\" 和 \"%s\" 相等\n", str1, str3);
    }
    
    return 0;
}

东巴文说明

  • 返回值 < 0:str1 < str2
  • 返回值 = 0:str1 = str2
  • 返回值 > 0:str1 > str2
  • 比较的是ASCII码值

strncmp - 部分比较

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

int main() {
    printf("=== 东巴文strncmp函数 ===\n\n");
    
    char str1[] = "apple pie";
    char str2[] = "apple tart";
    
    // strncmp: 比较前n个字符
    int result = strncmp(str1, str2, 5);
    
    printf("strncmp(\"%s\", \"%s\", 5) = %d\n", str1, str2, result);
    
    if (result == 0) {
        printf("前5个字符相等\n");
    }
    
    return 0;
}

字符串查找与定位

strchr - 查找字符

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

int main() {
    printf("=== 东巴文strchr函数 ===\n\n");
    
    char str[] = "东巴文欢迎您";
    char ch = '文';
    
    // strchr: 查找字符第一次出现的位置
    char *pos = strchr(str, ch);
    
    if (pos != NULL) {
        printf("找到'%c'在位置 %ld\n", ch, pos - str);
        printf("从该位置开始的字符串:%s\n", pos);
    } else {
        printf("未找到'%c'\n", ch);
    }
    
    return 0;
}

东巴文说明

  • strchr 查找字符第一次出现的位置
  • 返回指向该字符的指针
  • 如果未找到,返回 NULL

strrchr - 反向查找字符

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

int main() {
    printf("=== 东巴文strrchr函数 ===\n\n");
    
    char str[] = "东巴文欢迎您,东巴文";
    char ch = '文';
    
    // strrchr: 查找字符最后一次出现的位置
    char *pos = strrchr(str, ch);
    
    if (pos != NULL) {
        printf("找到最后一个'%c'在位置 %ld\n", ch, pos - str);
        printf("从该位置开始的字符串:%s\n", pos);
    } else {
        printf("未找到'%c'\n", ch);
    }
    
    return 0;
}

strstr - 查找子字符串

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

int main() {
    printf("=== 东巴文strstr函数 ===\n\n");
    
    char str[] = "东巴文欢迎您";
    char *substr = "欢迎";
    
    // strstr: 查找子字符串第一次出现的位置
    char *pos = strstr(str, substr);
    
    if (pos != NULL) {
        printf("找到\"%s\"在位置 %ld\n", substr, pos - str);
        printf("从该位置开始的字符串:%s\n", pos);
    } else {
        printf("未找到\"%s\"\n", substr);
    }
    
    return 0;
}

东巴文说明

  • strstr 查找子字符串第一次出现的位置
  • 返回指向子字符串的指针
  • 如果未找到,返回 NULL

strtok - 字符串分割

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

int main() {
    printf("=== 东巴文strtok函数 ===\n\n");
    
    char str[] = "东巴文,欢迎,您";
    char *token;
    
    // strtok: 分割字符串
    printf("分割字符串:\n");
    token = strtok(str, ",");
    while (token != NULL) {
        printf("  %s\n", token);
        token = strtok(NULL, ",");
    }
    
    return 0;
}

东巴文说明

  • strtok 会修改原字符串
  • 第一次调用传入字符串,后续调用传入 NULL
  • 使用分隔符集合分割字符串

字符串转换函数

atoi - 字符串转整数

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("=== 东巴文atoi函数 ===\n\n");
    
    char str1[] = "12345";
    char str2[] = "-67890";
    char str3[] = "123abc";
    
    // atoi: 字符串转整数
    int num1 = atoi(str1);
    int num2 = atoi(str2);
    int num3 = atoi(str3);
    
    printf("atoi(\"%s\") = %d\n", str1, num1);
    printf("atoi(\"%s\") = %d\n", str2, num2);
    printf("atoi(\"%s\") = %d\n", str3, num3);
    
    return 0;
}

东巴文说明

  • atoi 将字符串转换为整数
  • 忽略前导空白字符
  • 遇到非数字字符停止

atof - 字符串转浮点数

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("=== 东巴文atof函数 ===\n\n");
    
    char str1[] = "3.14159";
    char str2[] = "-2.71828";
    char str3[] = "123.456abc";
    
    // atof: 字符串转浮点数
    double num1 = atof(str1);
    double num2 = atof(str2);
    double num3 = atof(str3);
    
    printf("atof(\"%s\") = %.5f\n", str1, num1);
    printf("atof(\"%s\") = %.5f\n", str2, num2);
    printf("atof(\"%s\") = %.5f\n", str3, num3);
    
    return 0;
}

sprintf - 格式化字符串

#include <stdio.h>

int main() {
    printf("=== 东巴文sprintf函数 ===\n\n");
    
    char str[100];
    int age = 25;
    double score = 95.5;
    
    // sprintf: 格式化字符串
    sprintf(str, "年龄:%d,分数:%.1f", age, score);
    
    printf("格式化后的字符串:%s\n", str);
    
    return 0;
}

东巴文说明

  • sprintf 将格式化数据写入字符串
  • 类似 printf,但输出到字符串
  • 确保目标字符串有足够空间

sscanf - 从字符串读取

#include <stdio.h>

int main() {
    printf("=== 东巴文sscanf函数 ===\n\n");
    
    char str[] = "东巴文 25 95.5";
    char name[20];
    int age;
    double score;
    
    // sscanf: 从字符串读取格式化数据
    sscanf(str, "%s %d %lf", name, &age, &score);
    
    printf("姓名:%s\n", name);
    printf("年龄:%d\n", age);
    printf("分数:%.1f\n", score);
    
    return 0;
}

字符处理函数

tolower - 转小写

#include <stdio.h>
#include <ctype.h>

int main() {
    printf("=== 东巴文tolower函数 ===\n\n");
    
    char ch = 'A';
    
    // tolower: 转小写
    char lower = tolower(ch);
    
    printf("原字符:%c\n", ch);
    printf("转小写:%c\n", lower);
    
    return 0;
}

toupper - 转大写

#include <stdio.h>
#include <ctype.h>

int main() {
    printf("=== 东巴文toupper函数 ===\n\n");
    
    char ch = 'a';
    
    // toupper: 转大写
    char upper = toupper(ch);
    
    printf("原字符:%c\n", ch);
    printf("转大写:%c\n", upper);
    
    return 0;
}

字符分类函数

#include <stdio.h>
#include <ctype.h>

int main() {
    printf("=== 东巴文字符分类函数 ===\n\n");
    
    char ch = 'A';
    
    printf("字符'%c'的分类:\n", ch);
    printf("  isalpha: %d\n", isalpha(ch));
    printf("  isdigit: %d\n", isdigit(ch));
    printf("  isupper: %d\n", isupper(ch));
    printf("  islower: %d\n", islower(ch));
    printf("  isalnum: %d\n", isalnum(ch));
    printf("  isspace: %d\n", isspace(ch));
    
    return 0;
}

东巴文说明

  • isalpha - 是否为字母
  • isdigit - 是否为数字
  • isupper - 是否为大写字母
  • islower - 是否为小写字母
  • isalnum - 是否为字母或数字
  • isspace - 是否为空白字符

字符串处理函数的应用实例

字符串统计

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

int main() {
    printf("=== 东巴文字符串统计 ===\n\n");
    
    char str[] = "Hello, 东巴文! 123";
    
    int letters = 0, digits = 0, spaces = 0, others = 0;
    
    for (int i = 0; str[i] != '\0'; i++) {
        if (isalpha(str[i])) {
            letters++;
        } else if (isdigit(str[i])) {
            digits++;
        } else if (isspace(str[i])) {
            spaces++;
        } else {
            others++;
        }
    }
    
    printf("字符串:%s\n", str);
    printf("字母:%d\n", letters);
    printf("数字:%d\n", digits);
    printf("空格:%d\n", spaces);
    printf("其他:%d\n", others);
    
    return 0;
}

字符串分割与处理

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

int main() {
    printf("=== 东巴文字符串分割与处理 ===\n\n");
    
    char str[] = "东巴文,C语言,编程,学习";
    char *tokens[10];
    int count = 0;
    
    // 分割字符串
    char *token = strtok(str, ",");
    while (token != NULL && count < 10) {
        tokens[count] = token;
        count++;
        token = strtok(NULL, ",");
    }
    
    printf("分割结果:\n");
    for (int i = 0; i < count; i++) {
        printf("  %d: %s\n", i + 1, tokens[i]);
    }
    
    return 0;
}

字符串查找与替换

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

int main() {
    printf("=== 东巴文字符串查找与替换 ===\n\n");
    
    char str[] = "东巴文欢迎您";
    char *substr = "欢迎";
    char *replacement = "谢谢";
    
    // 查找子字符串
    char *pos = strstr(str, substr);
    
    if (pos != NULL) {
        printf("找到\"%s\"在位置 %ld\n", substr, pos - str);
        
        // 简单替换(需要目标字符串有足够空间)
        char result[100];
        int len = pos - str;
        
        // 复制前半部分
        strncpy(result, str, len);
        result[len] = '\0';
        
        // 连接替换字符串
        strcat(result, replacement);
        
        // 连接后半部分
        strcat(result, pos + strlen(substr));
        
        printf("替换后:%s\n", result);
    }
    
    return 0;
}

东巴文最佳实践

1. 使用安全函数

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

int main() {
    printf("=== 东巴文使用安全函数 ===\n\n");
    
    char dest[10];
    char src[] = "东巴文欢迎您";
    
    // ❌ 不安全:可能越界
    // strcpy(dest, src);
    
    // ✅ 安全:限制长度
    strncpy(dest, src, sizeof(dest) - 1);
    dest[sizeof(dest) - 1] = '\0';
    
    printf("安全复制:%s\n", dest);
    
    return 0;
}

2. 检查返回值

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

int main() {
    printf("=== 东巴文检查返回值 ===\n\n");
    
    char str[] = "东巴文欢迎您";
    char ch = '文';
    
    // ✅ 正确:检查返回值
    char *pos = strchr(str, ch);
    if (pos != NULL) {
        printf("找到'%c'在位置 %ld\n", ch, pos - str);
    } else {
        printf("未找到'%c'\n", ch);
    }
    
    return 0;
}

3. 字符串长度检查

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

int main() {
    printf("=== 东巴文字符串长度检查 ===\n\n");
    
    char str[50] = "东巴文";
    char append[] = "欢迎您";
    
    // ✅ 正确:检查剩余空间
    if (strlen(str) + strlen(append) < sizeof(str)) {
        strcat(str, append);
        printf("连接成功:%s\n", str);
    } else {
        printf("空间不足\n");
    }
    
    return 0;
}

东巴文验证清单

完成本章学习后,请确认:

  • 理解字符串处理函数的分类
  • 掌握字符串长度与复制函数
  • 掌握字符串连接与比较函数
  • 掌握字符串查找与定位函数
  • 掌握字符串转换函数
  • 掌握字符处理函数
  • 掌握字符串处理函数的应用
  • 掌握最佳实践

下一步学习

掌握字符串处理函数后,你可以继续学习:

如果遇到问题,欢迎访问 东巴文(db-w.cn) 获取帮助!


东巴文(db-w.cn) - 让编程学习更简单

🔧 东巴文字符串处理函数提示:字符串处理函数是C语言文本处理的利器,熟练掌握它们可以大大提高开发效率。在 db-w.cn,我们会通过大量实例帮你掌握字符串处理函数的使用!