strcspn是 C 语言标准库中的一个函数,用于查找字符串中不包含任何指定字符的初始段的长度。
strcspn 函数头文件
strcspn函数的头文件是<string.h>。在使用strcspn函数之前,确保在你的 C 代码中包含这个头文件:
#include <string.h>
strcspn 函数原型
size_t strcspn(const char* s1, const char* s2);
strcspn函数计算s1指向的字符串中最大初始段的长度,该初始段由s2指向的字符串中不包含的字符组成。
参数说明
s1:指向要搜索的字符串s2:包含要排除的字符的字符串;
返回值
strcspn函数返回初始段的长度;如果s1中不包含s2中的字符,返回s1的长度;
strcspn 示例代码
#include <stdio.h>
#include <string.h>
int main() {
const char* str1 = "Hello, world";
const char* str2 = "?Hello, world";
const char* str3 = "helloworld";
const char* chars = " ,?";
size_t result1 = strcspn(str1, chars);
size_t result2 = strcspn(str2, chars);
size_t result3 = strcspn(str3, chars);
printf("%ld\n%ld\n%ld\n", result1,result2,result3);
return 0;
}
程序运行结果
5 0 10