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。

posted @ 2012-11-02 08:27  N3verL4nd  阅读(208)  评论(0编辑  收藏  举报