首页 > 文章列表 > 在C语言中,字符串搜索函数是什么?

在C语言中,字符串搜索函数是什么?

c语言 函数 字符串搜索
219 2023-08-30

该库还提供了几个字符串搜索函数,如下 -

char *strchr (const char *string, intc);

查找字符串中第一次出现的字符 c。

char "strrchr (const char "string, intc);

查找字符串中最后一次出现的字符 c。

char *strpbrk (const char *s1,const char *s2);

返回一个指针,指向字符串 s1 中第一次出现字符串 s2 中的任何字符,或者如果 s1 中不存在 s2 中的字符,则返回空指针。

size_t strspn (const char *s1, const char *s2);

返回 s1 开头与 s2 匹配的字符数。

size_t strcspn (const char *51, const char *s2);

返回 s1 开头匹配 s2 的字符数。

char *strtok(c​​har *s1,const char *s2);

断开指向的字符串to 将 si 转换为一系列标记,每个标记由 s2 指向的字符串中的一个或多个字符分隔。

char * strtok_r(char *s1,const char *s2, char

与strtok()功能相同,除了**lasts);指向字符串占位符的指针必须由调用者提供。

strchr () 和 strrchr () 是最简单的使用。

示例 1

以下是字符串搜索函数的 C 程序 -

 实时演示

#include <string.h>
#include <stdio.h>
void main(){
   char *str1 = "Hello";
   char *ans;
   ans = strchr (str1,'l');
   printf("%s

", ans); }

输出

当执行上述程序时,会产生以下结果 -

llo

执行完此操作后,ans 指向位置 str1 + 2。

strpbrk () 是一个更通用的函数,用于搜索任意一组中的第一次出现的位置

示例 2

以下是使用 strpbrk () 函数的 C 程序 -

 Live Demo

#include <string.h>
#include <stdio.h>
void main(){
   char *str1 = "Hello";
   char *ans;
   ans = strpbrk (str1,"aeiou");
   printf("%s

",ans); }

输出

当执行上述程序时,会产生以下结果 -

ello

这里,ans指向位置str1 + 1,即第一个e的位置。