2026/08/19 常用的字符串处理接口

一般关于程序中的字符串的处理接口有很多,常用的有strlen、strcmp、strncmp、strcpy、strcat、strncat、strstr、strtok、atoi、sprintf.........

函数 主要作用 头文件
strlen 求字符串长度 <string.h>
strcmp 比较两个字符串 <string.h>
strncmp 比较前 N 个字符 <string.h>
strcpy 字符串复制 <string.h>
strcat 字符串拼接 <string.h>
strncat 拼接指定数量字符 <string.h>
strstr 查找子字符串 <string.h>
strtok 字符串分割 <string.h>
atoi 字符串转整数 <stdlib.h>
sprintf 格式化字符串 <stdio.h>

1.strlen —— 获取字符串长度
函数原型 size_t strlen(const char *s);
作用:计算字符串中有效字符的数量。
例如:

char str[] = "hello";
printf("%ld\n", strlen(str));

结果:5

注意:hello
实际上内存中是:h e l l o \0
strlen() 不计算最后的 \0。
在计算汉字时strlen() 计算的是字节数,不是汉字个数

2.strcmp —— 比较两个字符串
函数原型 int strcmp(const char *s1, const char *s2);
返回值:
= 0 a和b相同
< 0 a小于b
> 0 a大于b

所以不要写:if(strcmp(str1,str2))来判断相等。
应该:if(strcmp(str1,str2) == 0)
例如:

char str1[] = "hello";
char str2[] = "hello";
if(strcmp(str1, str2) == 0)
{
    printf("两个字符串相同\n");
}

结果:
两个字符串相同

典型应用:登录验证
例如:

char username[20] = "admin";
if(strcmp(username, "admin") == 0)
{
    printf("用户名正确\n");
}

3.strncmp —— 比较前n个字符
函数原型 int strncmp(const char *s1, const char *s2, size_t n);

例如:

char str1[] = "hello123";
char str2[] = "hello456";
if(strncmp(str1, str2, 5) == 0)
{
    printf("前5个字符相同\n");
}

结果:前5个字符相同

因为:
hello123
hello456
^^^^^
前 5 个字符都是:hello

典型用途
例如判断命令

char cmd[] = "LED_ON";
if(strncmp(cmd, "LED", 3) == 0)
{
    printf("这是LED相关命令\n");
}

4.strcpy —— 字符串复制
函数原型 char *strcpy(char *dest, const char *src);

例如:

char src[] = "hello";
char dest[20];
strcpy(dest, src);
printf("%s\n", dest);

结果:

hello

执行之后:

src

hello\0

dest

hello\0
注意目标空间必须足够

5.strcat —— 字符串拼接

函数原型 char *strcat(char *dest, const char *src);

例如:

char str[30] = "hello ";
strcat(str, "world");
printf("%s\n", str);

结果:

hello world

原来:hello \0
执行:strcat(str, "world")之后:
hello world\0

目标数组必须足够大

6.strncat —— 拼接指定数量字符
函数原型 char *strncat(char *dest, const char *src, size_t n);

例如:

char str[30] = "hello ";
strncat(str, "abcdef", 3);
printf("%s\n", str);

结果:hello abc

使用时仍然要计算空间。

7.strstr —— 查找子字符串
函数原型 char *strstr(const char *haystack, const char *needle);
返回值:
如果找到则返回子字符串第一次出现的位置。
如果没找到:return NULL;

例如串口收到temperature=25

可以:

if(strstr(buf, "temperature") != NULL)
{
    printf("收到温度数据\n");
}

例如:

char str[] = "hello world";
char *p = strstr(str, "world");
if(p != NULL)
{
    printf("找到了:%s\n", p);
}

输出:
找到了:world

8.atoi —— 字符串转换成整数
函数原型 int atoi(const char *nptr);

例如:

char str[] = "123";
int num = atoi(str);
printf("%d\n", num);

结果:123

atoi() 对错误输入的检测能力比较弱。

例如:atoi("123abc")
通常得到:123

9.strtok —— 字符串分割
函数原型 char *strtok(char *str, const char *delim);
该函数可将字符串分解为一连串零个或多个非空标记。首次调用时,需通过str参数指定待解析的字符串。在后续每次应解析同一字符串的调用中,str参数必须设为NULL
例如有char str[] = "zhangsan,20,master";
想拆成:
zhangsan
20
master

可以:

char str[] = "zhangsan,20,master";
char *p = strtok(str, ",");
while(p != NULL)
{
    printf("%s\n", p);
    p = strtok(NULL, ",");
}

输出:

zhangsan
20
master

strtok 会修改原字符串
例如:char str[] = "abc,def,ghi";

调用后实际上会把:‘,’替换成:\0

所以:

不能把字符串常量直接传给 strtok()。

错误:strtok("abc,def", ",");

delim 可以是一组字符

例如:char str[]="hello world-linux";

如果:strtok(str," -");

表示:空格或者 - 都是分隔符。

结果:
hello
world
linux

因为:空格 -都会被识别。

10.sprintf —— 格式化字符串
函数原型 int sprintf(char *str, const char *format, ...);

例如:

char buf[100];
int year = 2026;
int month = 8;
int day = 19;
sprintf(buf, "%d年%d月%d日", year, month, day);
printf("%s\n", buf);

结果:2026年8月19日

下面把所有函数串起来做一个完整案例

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

int main()
{
    /**************************************
     * 原始数据
     **************************************/
    char data[] = "USER:admin,AGE:24,CMD:LED_ON,MSG:hello";
    /**************************************
     * 1. strlen
     * 获取字符串长度
     **************************************/
    printf("原始字符串长度:%lu\n", strlen(data));
    /**************************************
     * 2. strcpy
     * 复制字符串
     **************************************/
    char backup[100];
    strcpy(backup, data);
    printf("复制后的字符串:%s\n", backup);
    /**************************************
     * 3. strstr
     * 查找 CMD
     **************************************/
    char *p = strstr(data, "CMD");
    if(p != NULL)
    {
        printf("找到了CMD:%s\n", p);
    }
    /**************************************
     * 4. strtok
     * 按逗号分割字符串
     **************************************/
    char *token;
    token = strtok(data, ",");
    char username[20] = "";
    int age = 0;
    char command[30] = "";
    char message[50] = "";
    while(token != NULL)
    {
        printf("分割结果:%s\n", token);

        if(strncmp(token, "USER:", 5) == 0)
        {
            strcpy(username, token + 5);
        }


        /**********************************
         * AGE
         **********************************/

        else if(strncmp(token, "AGE:", 4) == 0)
        {
            age = atoi(token + 4);
        }


        /**********************************
         * CMD
         **********************************/

        else if(strncmp(token, "CMD:", 4) == 0)
        {
            strcpy(command, token + 4);
        }


        /**********************************
         * MSG
         **********************************/

        else if(strncmp(token, "MSG:", 4) == 0)
        {
            strcpy(message, token + 4);
        }


        token = strtok(NULL, ",");
    }


    /**************************************
     * 5. strcmp
     * 判断用户名
     **************************************/

    if(strcmp(username, "admin") == 0)
    {
        printf("用户名正确\n");
    }
    else
    {
        printf("用户名错误\n");
    }


    /**************************************
     * 6. strncmp
     * 判断命令
     **************************************/

    if(strncmp(command, "LED", 3) == 0)
    {
        printf("这是LED控制命令\n");
    }


    /**************************************
     * 7. strcat
     * 字符串拼接
     **************************************/

    char result[200] = "用户:";

    strcat(result, username);

    printf("strcat结果:%s\n", result);


    /**************************************
     * 8. strncat
     * 拼接指定数量字符
     **************************************/

    strcat(result, ",消息:");

    strncat(result, message, 5);

    printf("strncat结果:%s\n", result);


    /**************************************
     * 9. sprintf
     * 格式化最终字符串
     **************************************/

    char output[200];

    sprintf(output,
            "用户=%s 年龄=%d 命令=%s 消息=%s",
            username,
            age,
            command,
            message);


    printf("\n最终结果:\n");

    printf("%s\n", output);


    return 0;
}

这个程序的执行流程

原始数据:USER:admin,AGE:24,CMD:LED_ON,MSG:hello

首先:strlen(data)得到字符串长度。
然后:strcpy(backup, data);复制一份数据。
接下来:strstr(data, "CMD");找到:CMD:LED_ON,MSG:hello
然后:strtok(data, ",");第一次得到:USER:admin
第二次:AGE:24第三次:CMD:LED_ON第四次:MSG:hello
对于:USER:admin执行:strncmp(token, "USER:", 5)判断前 5 个字符是不是:SER:
然后:strcpy(username, token + 5);
注意这里:
token

USER:admin
0123456789
所以token + 5指向:admin
对于:AGE:24执行:atoi(token + 4);相当于:atoi("24");
最终:age = 24;
对于:CMD:LED_ON最终:command = "LED_ON";
最后:
sprintf(output,
"用户=%s 年龄=%d 命令=%s 消息=%s",
username,
age,
command,
message);
得到:用户=admin 年龄=24 命令=LED_ON 消息=hello

posted @ 2026-08-19 17:25  !城北徐公.!  阅读(3)  评论(0)    收藏  举报