当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ strcspn()用法及代码示例


C /C++中的strcspn()函数将两个字符串作为输入,即string_1和string_2作为参数,并通过遍历string_2中存在的任何字符来搜索string_1。如果在string_1中找不到string_2的任何字符,则该函数将返回string_1的长度。此函数在cstring头文件中定义。

用法:

size_t strcspn ( const char *string_1, const char *string_2 ) 

参数:该函数接受两个强制性参数,如下所述:


  • string_1:指定要搜索的字符串
  • string_2:指定包含要匹配的字符的字符串

返回值:此函数返回从string_2匹配的任何字符之前在string_1中遍历的字符数。

以下示例程序旨在说明上述函数:

程序1:

// C++ program to illustrate the 
// strcspn() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // String to be travered 
    char string_1[] = "geekforgeeks456"; 
  
    // Search these characters in string_1 
    char string_2[] = "123456789"; 
  
    // function strcspn() traverse the string_1 
    // and search the characters of string_2 
    size_t match = strcspn(string_1, string_2); 
  
    // if matched return the position number 
    if (match < strlen(string_1)) 
        cout << "The number of characters before"
             << "the matched character are " << match; 
  
    else
        cout << string_1 <<  
        " didn't matched any character from string_2 "; 
    return 0; 
}
输出:
The number of characters beforethe matched character are 12

程序2:

// C++ program to illustrate the 
// strcspn() function When the string 
// containing the character to be 
// matched is empty 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // String to be travered 
    char string_1[] = "geekforgeeks456"; 
  
    // Search these characters in string_1 
    char string_2[] = ""; // Empty 
  
    // function strcspn() traverse the string_1 
    // and search the characters of string_2 
    size_t match = strcspn(string_1, string_2); 
  
    // if matched return the position number 
    if (match < strlen(string_1)) 
        cout << "The number of character before"
             << "the matched character are " << match; 
    else
        cout << string_1 <<  
        " didn't matched any character from string_2  "; 
    return 0; 
}
输出:
geekforgeeks456 didn't matched any character from string_2


相关用法


注:本文由纯净天空筛选整理自AmanSrivastava1大神的英文原创作品 strcspn() function in C/C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。