C语言中的字符串搜索函数是什么?
C语言中的字符串搜索函数
该库还提供了一些字符串搜索函数,如下所示:
| char *strchr (const char *string, int c); |
查找字符串中字符c的第一次出现。 |
| char *strrchr (const char *string, int c); |
查找字符串中字符c的最后一次出现。 |
| char *strpbrk (const char *s1, const char *s2); |
返回指向字符串s1中s2中任何字符的第一次出现的指针,如果s2中的任何字符都不存在于s1中,则返回空指针。 |
| size_t strspn (const char *s1, const char *s2); |
返回s1开头与s2匹配的字符数。 |
| size_t strcspn (const char *s1, const char *s2); |
返回s1开头**不**匹配s2的字符数。 |
| char *strtok (char *s1, const char *s2); |
将s1指向的字符串分解成一系列标记,每个标记都由s2指向的字符串中的一个或多个字符分隔。 |
| char *strtok_r (char *s1, const char *s2, char *lasts); |
与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程序:
#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的位置。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP