C語言strspn()函數:計算字符串str中連續有幾個字符都屬于字符串accept
頭文件:#include <string.h>
strspn() 函數用來計算字符串 str 中連續有幾個字符都屬于字符串 accept,其原型為:
size_t strspn(const char *str, const char * accept);
【函數說明】strspn() 從參數 str 字符串的開頭計算連續的字符,而這些字符都完全是 accept 所指字符串中的字符。簡單的說,若 strspn() 返回的數值為n,則代表字符串 str 開頭連續有 n 個字符都是屬于字符串 accept 內的字符。
【返回值】返回字符串 str 開頭連續包含字符串 accept 內的字符數目。所以,如果 str 所包含的字符都屬于 accept,那么返回 str 的長度;如果 str 的第一個字符不屬于 accept,那么返回 0。
注意:檢索的字符是區分大小寫的。
提示:提示:函數 strcspn() 的含義與 strspn() 相反,可以對比學習。
范例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #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; } |
執行結果:
1 | str 前 3 個字符都屬于 accept |
C語言strcspn()函數:計算字符串str中連續有幾個字符都不屬于字符串accept
頭文件:#inclued<string.h>
strcspn() 用來計算字符串 str 中連續有幾個字符都不屬于字符串 accept,其原型為:
1 | int strcspn ( char *str, char *accept); |
【參數說明】str、accept為要進行查找的兩個字符串。
strcspn() 從字符串 str 的開頭計算連續的字符,而這些字符都完全不在字符串 accept 中。簡單地說,若 strcspn() 返回的數值為 n,則代表字符串 str 開頭連續有 n 個字符都不含字符串 accept 中的字符。
【返回值】返回字符串 str 開頭連續不含字符串 accept 內的字符數目。
注意:如果 str 中的字符都沒有在 accept 中出現,那么將返回 atr 的長度;檢索的字符是區分大小寫的。
提示:函數 strspn() 的含義與 strcspn() 相反,可以對比學習。
【示例】返回s1、s2包含的相同字符串的位置。
1 2 3 4 5 6 7 8 9 10 11 12 13 | #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; } |
運行結果:
1 2 | The first char both in s1 and s2 is :c The position in s1 is: 7 |
再看一個例子,判斷兩個字符串的字符是否有重復的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #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; } |
運行結果:
1 | s1 is diffrent from s2! |