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


strchr,strrchr, strchrnul 定位一個字符

strchr系列函數介紹

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

區別在於:
strchr 從左向右找,第一個出現字符c的位置即為所求;
strrchr 從右向左找,第一個出現字符c的位置即為所求(即字符串最后一個出現字符c的位置);
strchrnul 類似於strchr,除了當沒有找到字符c時,返回null終結符('\0')所在位置,而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,根據最后一個路徑分隔符'/',提取出文件名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\n", file_path);
        exit(1);
    }

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

    printf("file name is %s\n", 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\n", file_path);
    }
    else {
        printf("file %s is not txt format\n", file_path);
    }

    return 0;
}

運行結果:

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

strtok, strtok_r 字符串切分

參見這篇文章:Linux C strtok實現自定義字符串切分函數split


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM