📅  最后修改于: 2023-12-03 14:59:36.060000             🧑  作者: Mango
strcspn()
函数是C/C++标准库函数中的一个字符串函数,用于在一个字符串中查找第一次出现某些字符集合中任意字符的位置。
size_t strcspn(const char *str1, const char *str2);
strcspn()
函数会在str1
所指向的字符串中查找第一个匹配str2
所指向字符串中任一字符的字符。如果没有出现匹配字符,函数返回str1
所指向字符串的长度;否则,返回从str1
开始到第一个匹配字符之间的长度。
str1
:要查找的字符串,即源字符串。str2
:要查找的字符集合。str1
到第一个匹配字符之间的长度。#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "hello world";
char str2[] = "lo";
int len = strcspn(str1, str2);
printf("The length of the initial segment in str1 without any character from str2 is %d", len);
return 0;
}
输出结果为:
The length of the initial segment in str1 without any character from str2 is 3
在此示例中,strcspn()
函数搜索str1
中的字符,直到遇见str2
中任何一个字符,结果返回了从str1
开头到第一个匹配字符之间的字符数(即hel
的长度为3)。
strcspn()
函数在查找时,匹配的字符集合为str2
中任意一个字符,不是整个字符串。strcspn()
函数来查找某个“标签”的结束位置。