该函数strcspn()计算两个字符串中首次匹配的字符之前的字符数。这在“ string.h”头文件中声明。它返回出现第一个匹配字符之前的第一个字符串的字符数。
这是strcspn()C语言的语法,
size_t strcspn(const char *string1, const char *string2)
这里,
string1-要扫描的第一个字符串。
string2-第二个字符串,用于搜索第一个字符串中的匹配字符。
这是strcspn()C语言的示例,
#include<stdio.h>
#include<string.h>
int main() {
char str1[] = "Helloworld!";
char str2[] = "work";
int result = strcspn(str1, str2);
printf("Number of characters before matching character : %d\n", (result+1));
return 0;
}输出结果
Number of characters before matching character : 5
在上面的程序中,声明了两个char类型的数组,并将字符串传递给它们。该功能strcspn()正在计算首次匹配之前的字符数“ wor”。因此,第一个字符串中有5个字符不匹配。因此,输出为5,并存储在可变结果中。
char str1[] = "Helloworld!"; char str2[] = "work"; int result = strcspn(str1, str2);