當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。