字符串相关函数及输出错误码信息

1. strcat()

将源字符串(src)追加到目标字符串(dest)的末尾

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

int main() {
   char dest[20] = "Hello";
   char src[] = " World!";
   strcat(dest, src);  // 将 src 追加到 dest
   printf("Result: %s\n", dest);  // 输出: Hello World!
   return 0;
}

2. strncat()

将源字符串(src)的前 n 个字符追加到目标字符串(dest)的末尾

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

int main() {
    char dest[20] = "Hello";
    char src[] = " World!";
    strncat(dest, src, 3);  // 将 src 的前 3 个字符追加到 dest
    printf("Result: %s\n", dest);  // 输出: Hello Wo
    return 0;
}

3. strstr()

在字符串 haystack 中查找子字符串 needle 的第一次出现位置

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

int main() {
    const char *haystack = "Hello World!";
    const char *needle = "World";
    char *result = strstr(haystack, needle);
    if (result) {
        printf("Found: %s\n", result);  // 输出: Found: World!
    } else {
        printf("Not found!\n");
    }
    return 0;
}

4. strtok()

将字符串 str 按照指定的分隔符(delim)分割成多个子字符串(标记)

  • 第一次调用时,str 是要分割的字符串;后续调用时,str 应为 NULL
  • strtok 会修改原始字符串,将分隔符替换为 \0
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "Hello,World,How,Are,You";
    const char *delim = ",";
    char *token = strtok(str, delim);
    while (token) {
        printf("Token: %s\n", token);
        token = strtok(NULL, delim);
    }
    return 0;
}

5. strerror()

返回错误码对应的错误信息字符串

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

int main() {
    FILE *file = fopen("nonexistent_file.txt", "r");
    if (!file) {
        printf("Error: %s\n", strerror(errno));  // 输出错误信息
    }
    return 0;
}

6. perror()

打印自定义信息以及会将错误码转化为错误信息输出

int main() 
{
	FILE* pf = fopen("test.txt", "r");
    if(pf == NULL)
    {
        perror("fopen");
    }
}

🦀🦀观看~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值