C 庫 - strcspn() 函式



C 庫的 strcspn() 函式接受兩個指標變數作為引數,計算初始段(str1)的長度,並且該段完全由不在 str2 中的字元組成。

通常,它用於查詢給定字串的長度,並返回從開頭開始的字元數。

語法

以下是 C 庫 strcspn() 函式的語法:

size_t strcspn(const char *str1, const char *str2)

引數

此函式接受以下引數:

  • str1 - 這是要掃描的主 C 字串。

  • str2 - 這是一個包含與 str1 匹配的字元列表的字串。

返回值

此函式返回字串 str1 的初始段的長度,該段不包含字串 str2 中的任何字元。

示例 1

以下 C 庫程式說明了 strcspn() 函式如何檢查字串中的第一個不匹配字元。

#include <stdio.h>
#include <string.h>

int main () {
   int len;
   // Intializing string(Unmatched Characters)
   const char str1[] = "Tutorialspoint";
   const char str2[] = "Textbook";

   len = strcspn(str1, str2);

   printf("First matched character is at %d\n", len + 1);
   
   return(0);
}

輸出

以上程式碼產生以下結果:

First matched character is at 10

示例 2

我們使用 strcspn() 方法來顯示匹配的字元。

#include <stdio.h>
#include <string.h>

int main() {
   int size;

   // Intializing string(Matched Characters)
   char str1[] = "tutorialspoint";
   char str2[] = "tutorial"; 
    
   // Using strcspn() to 
   size = strcspn(str1, str2);
    
   printf("The unmatched characters before the first matched character: %d\n", size);
   return 0;
}

輸出

以上程式碼產生以下結果:

The unmatched characters before the first matched character: 0

示例 3

這裡,我們使用 strcspn() 函式確定不包含給定集合中任何字元的初始段的長度。

#include <stdio.h> 
#include <string.h> 
  
int main() {  
   char str1[] = "Welcome to Tutorialspoint Community";  
   char str2[] = "point";  
  
   size_t len = strcspn(str1, str2); 
   // Display the output 
   printf("The length of the initial segment of str1 that does not contain any characters from str2 is: %zu\n", len);  
   return 0;  
}  

輸出

以上程式碼產生以下結果:

The length of the initial segment of str1 that does not contain any characters from str2 is: 4
廣告

© . All rights reserved.