strcspn函数

 函数原型:extern int strcspn(char *str1,char *str2)

参数说明:str1为参照字符串,即str2中每个字符分别与str1中的每个字符比较。
       
所在库名:#include <string.h>
 
函数功能:以str1为参照,比较字符串str2中的字符是否与str中某个字符相等(也就是检索str2中的字符是否在str1中存在),如果第一次发现相等,则停止并返回在str1中这个匹配相等的字符的索引值,失败则返回str1的长度。
 
返回说明:返回在str1中这个匹配相等的字符的索引值,是一个整数值。

其它说明:暂时无。

实例:

第一种情形(匹配能够成功):

#include  < string .h >
#include 
< stdio.h >
int  main()
{
    
char *str1="aaaaakkkeeee";  
    
char *str2="John,he like writing!"

    
int inttemp;

    inttemp
=strcspn(str1,str2);   //将str2中的每个字符均与str1中的匹配,如果这个字符在str1中出现过,则返回这个字符在str1中的索引值
     printf("The first index of the character both in str1 and str2: %d  ", inttemp);
    
return 0;
}

在VC++ 6.0编译运行:

匹配过程是这样的:

str2中第一个字符“J”先与str1中的每个字符比较,发现没有相同的;

继续,str2中的“o”再与str1中的每个字符比较,发现仍然没有相同的;

继续,……

当继续到str2中的字符“k”时,在与str1中索引位置为5的字符比较时第一次发现相等,终止搜索,返回索引值5;

结束。

第二种情形(匹配失败):

#include  < string .h >
#include 
< stdio.h >
int  main()
{
    
char *str1="aaaaakkkeeee";    //str1与str2中没有相同的字符
    char *str2="bbbcccddd"

    
int inttemp;

    inttemp
=strcspn(str1,str2);   //用strcspn函数
     printf("The first index of the character both in str1 and str2: %d  ", inttemp);
    
return 0;
}

在VC++ 6.0编译运行:

由于str1与str2中没有相同的字符,匹配失败,返回字符串str1的长度12。

 

`strcspn` 函数是 C 标准库中的一个字符串处理函数,用于计算字符串中第一个出现在指定字符集中的字符的位置。它的原型如下: ```c size_t strcspn(const char *str1, const char *str2); ``` ### 参数 - `str1`:要搜索的字符串。 - `str2`:包含要查找的字符的字符串。 ### 返回值 `strcspn` 函数返回 `str1` 中第一个出现在 `str2` 中的字符的位置。如果没有找到任何字符,则返回 `str1` 的长度。 ### 作用 `strcspn` 函数用于查找字符串 `str1` 中第一个出现在 `str2` 中的字符的位置。它可以用于多种场景,例如验证字符串中的字符是否合法,或者在字符串中查找特定字符的位置。 ### 示例代码 以下是一个使用 `strcspn` 函数的示例: ```c #include <stdio.h> #include <string.h> int main() { const char *str1 = "Hello, World!"; const char *str2 = "abc"; size_t pos = strcspn(str1, str2); if (pos < strlen(str1)) { printf("第一个在 '%s' 中出现的字符是 '%c',位置是 %zu\n", str2, str1[pos], pos); } else { printf("在 '%s' 中没有找到 '%s' 中的任何字符\n", str1, str2); } return 0; } ``` ### 解释 在上述代码中,`str1` 是要搜索的字符串,`str2` 是包含要查找的字符的字符串。`strcspn` 函数会返回 `str1` 中第一个出现在 `str2` 中的字符的位置。在这个例子中,`str2` 是 `"abc"`,所以 `strcspn` 会查找 `str1` 中第一个出现的 `'a'`、`'b'` 或 `'c'`。由于 `str1` 中没有这些字符,`strcspn` 会返回 `str1` 的长度。 如果我们将 `str2` 改为 `"oW!"`,那么 `strcspn` 会返回第一个出现在 `str2` 中的字符的位置,即 `'o'` 的位置。 ### 注意事项 - `strcspn` 函数不会修改输入字符串。 - 如果 `str1` 或 `str2` 为空指针,行为未定义。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值