- C標準庫
- C庫 - 首頁
- C庫 - <assert.h>
- C庫 - <complex.h>
- C庫 - <ctype.h>
- C庫 - <errno.h>
- C庫 - <fenv.h>
- C庫 - <float.h>
- C庫 - <inttypes.h>
- C庫 - <iso646.h>
- C庫 - <limits.h>
- C庫 - <locale.h>
- C庫 - <math.h>
- C庫 - <setjmp.h>
- C庫 - <signal.h>
- C庫 - <stdalign.h>
- C庫 - <stdarg.h>
- C庫 - <stdbool.h>
- C庫 - <stddef.h>
- C庫 - <stdio.h>
- C庫 - <stdlib.h>
- C庫 - <string.h>
- C庫 - <tgmath.h>
- C庫 - <time.h>
- C庫 - <wctype.h>
- C程式設計資源
- C程式設計 - 教程
- C - 有用資源
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
廣告