Linux C 字符串查找相关操作 strchr, strstr, strtok

strchr,strrchr, strchrnul 定位一个字符

strchr系列函数介绍

strchr 定位一个字符在字符串中的位置。
同系列函数有,strrchr,strchrnul。

区别在于:
strchr 从左向右找,第一个出现字符c的位置即为所求;
strrchr 从右向左找,第一个出现字符c的位置即为所求(即字符串最后一个出现字符c的位置);
strchrnul 类似于strchr,除了当没有找到字符c时,返回null终结符('')所在位置,而strchr没有找到c时,返回的是NULL;

注意:null终结符也属于字符串的一部分。

#include <string.h>

char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);

#define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <string.h>

char *strchrnul(const char *s, int c);
  • 功能
    在字符串s中,查找字符c所在位置

  • 参数
    s 待查找的字符串

c 待查找字符

  • 返回值
    查找成功时,返回一个指向字符c的指针;失败时,strchr和strrchr返回NULL,strchrnul返回指向null终结符的指针;

示例:在指定文件路径中,提取出文件名

使用strrchr,从指定文件路径/home/martin/workspace/test.txt,根据最后一个路径分隔符'/',提取出文件名。

/**
 * 从文件路径字符串提取文件名的示例程序
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

int main()
{
    char *file_path = "/home/martin/workspace/test.txt";
    char *seperator_pos = strrchr(file_path, '/');
    char file_name[256];

    if (seperator_pos == NULL) {
        fprintf(stderr, "Not a valid file path: %s
", file_path);
        exit(1);
    }

    char *p = seperator_pos + 1;
    int i = 0;
    while (*p != '') {
        file_name[i++] = *p;
        p++;
    }
    file_name[i] = '';

    printf("file name is %s
", file_name);

    return 0;
}

运行结果:

$ ./a.out 
file name is test.txt

strstr, strcasestr 定位一个子字符串

strstr, strcasestr函数介绍

strstr 定位一个子字符串needle,在字符串haystack中首次出现的位置。
同系列函数strcasestr,区别在于:
strstr 区别子字符串、字符串的大小写,strcasestr会忽略大小写。

#include <string.h>

char *strstr(const char *haystack, const char *needle);

#define _GNU_SOURCE         /* See feature_test_macros(7) */

#include <string.h>

char *strcasestr(const char *haystack, const char *needle);
  • 功能
    查找子字符串needle在字符串haystack首次出现位置

  • 参数
    haystack 被匹配的字符串

needle 待查找的子字符串

  • 返回值
    成功时,返回子字符串needle 在haystack 首次出现位置指针;失败时,返回NULL

示例:判断指定路径的文件是否为txt格式

/**
 * 判断指定文件路径的是否为txt格式(通过后缀名判断)的示例程序
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>


int is_format(const char *file_path, const char *file_format)
{
    char *pos = strstr(file_path, file_format);
    if (pos == NULL) {
        return 0;
    }
    return 1;
}

int main()
{
    char *file_path = "/home/martin/workspace/test.txt";
    if (is_format(file_path, "txt")) {
        printf("file %s is txt format
", file_path);
    }
    else {
        printf("file %s is not txt format
", file_path);
    }

    return 0;
}

运行结果:

$ ./a.out 
file /home/martin/workspace/test.txt is txt format

strtok, strtok_r 字符串切分

参加Linux C strtok实现自定义字符串切分函数split

原文地址:https://www.cnblogs.com/fortunely/p/15063066.html