C語言中strspn()函數(shù)和strcspn()函數(shù)的對比使用
C語言strspn()函數(shù):計算字符串str中連續(xù)有幾個字符都屬于字符串a(chǎn)ccept
頭文件:#include <string.h>
strspn() 函數(shù)用來計算字符串 str 中連續(xù)有幾個字符都屬于字符串 accept,其原型為:
size_t strspn(const char *str, const char * accept);
【函數(shù)說明】strspn() 從參數(shù) str 字符串的開頭計算連續(xù)的字符,而這些字符都完全是 accept 所指字符串中的字符。簡單的說,若 strspn() 返回的數(shù)值為n,則代表字符串 str 開頭連續(xù)有 n 個字符都是屬于字符串 accept 內的字符。
【返回值】返回字符串 str 開頭連續(xù)包含字符串 accept 內的字符數(shù)目。所以,如果 str 所包含的字符都屬于 accept,那么返回 str 的長度;如果 str 的第一個字符不屬于 accept,那么返回 0。
注意:檢索的字符是區(qū)分大小寫的。
提示:提示:函數(shù) strcspn() 的含義與 strspn() 相反,可以對比學習。
范例:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main () { int i; char str[] = "129th"; char accept[] = "1234567890"; i = strspn(str, accept); printf("str 前 %d 個字符都屬于 accept\n",i); system("pause"); return 0; }
執(zhí)行結果:
str 前 3 個字符都屬于 accept
C語言strcspn()函數(shù):計算字符串str中連續(xù)有幾個字符都不屬于字符串a(chǎn)ccept
頭文件:#inclued<string.h>
strcspn() 用來計算字符串 str 中連續(xù)有幾個字符都不屬于字符串 accept,其原型為:
int strcspn(char *str, char *accept);
【參數(shù)說明】str、accept為要進行查找的兩個字符串。
strcspn() 從字符串 str 的開頭計算連續(xù)的字符,而這些字符都完全不在字符串 accept 中。簡單地說,若 strcspn() 返回的數(shù)值為 n,則代表字符串 str 開頭連續(xù)有 n 個字符都不含字符串 accept 中的字符。
【返回值】返回字符串 str 開頭連續(xù)不含字符串 accept 內的字符數(shù)目。
注意:如果 str 中的字符都沒有在 accept 中出現(xiàn),那么將返回 atr 的長度;檢索的字符是區(qū)分大小寫的。
提示:函數(shù) strspn() 的含義與 strcspn() 相反,可以對比學習。
【示例】返回s1、s2包含的相同字符串的位置。
#include<stdio.h> #include <stdlib.h> #include<string.h> int main() { char* s1 = "http://c.biancheng.net/cpp/u/biaozhunku/"; char* s2 = "c is good"; int n = strcspn(s1,s2); printf("The first char both in s1 and s2 is :%c\n",s1[n]); printf("The position in s1 is: %d\n",n); system("pause"); return 0; }
運行結果:
The first char both in s1 and s2 is :c The position in s1 is: 7
再看一個例子,判斷兩個字符串的字符是否有重復的。
#include<stdio.h> #include <stdlib.h> #include<string.h> int main() { char* s1 = "http://c.biancheng.net/cpp/xitong/"; char* s2 = "z -+*"; if(strlen(s1) == strcspn(s1,s2)){ printf("s1 is diffrent from s2!\n"); }else{ printf("There is at least one same character in s1 and s2!\n"); } system("pause"); return 0; }
運行結果:
s1 is diffrent from s2!
相關文章
vscode+platformIO開發(fā)stm32f4的實現(xiàn)
這篇文章主要介紹了vscode+platformIO開發(fā)stm32f4的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05