C庫 - strspn() 函式



C庫函式`strspn()`用於查詢僅包含另一個字串(str2)中存在的字元的字首(str1)的長度。

它透過接受任意兩個字串作為輸入,允許輕鬆定製。因此,這使得能夠比較不同的字元集和字串。

語法

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

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

引數

此函式接受以下引數:

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

  • str2 − 這是包含要在str1中匹配的字元列表的字串。

返回值

此函式返回str1初始段中僅由str2中的字元組成的字元數。

示例1

我們使用C庫函式`strspn()`演示了對給定字串中兩個字首子串的比較,並找到其長度。

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

int main () {
   int len;
   const char str1[] = "ABCDEFG019874";
   const char str2[] = "ABCD";

   len = strspn(str1, str2);

   printf("Length of initial segment matching %d\n", len );
   
   return(0);
}

輸出

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

Length of initial segment matching 4

示例2

下面的C程式使用函式`strspn()`從給定字串中過濾掉非字母字元。(原文此處似乎有誤,應為strspn())

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

const char* low_letter = "qwertyuiopasdfghjklzxcvbnm";

int main() {
   char s[] = "tpsde312!#$";

   size_t res = strspn(s, low_letter);
   printf("After skipping initial lowercase letters from '%s'\nThe remainder becomes '%s'\n", s, s + res);
   
   return 0;
}

輸出

程式碼執行後,我們得到以下結果:

After skipping initial lowercase letters from 'tpsde312!#$'
The remainder becomes '312!#$'

示例3

下面的程式說明了使用`strspn()`查詢主字串中字首子串的長度。

#include <stdio.h>
#include <string.h> 
  
int main () { 
   int leng = strspn("We are Vertos", "We"); 
   printf("Length of initial characters matching : %d\n", leng );     
   return 0; 
} 

輸出

執行上述程式碼後,我們得到以下結果:

Length of initial characters matching : 2
廣告
© . All rights reserved.