C语言中strspn()函数和strcspn()函数的对比使用
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 內(nèi)的字符。
【返回值】返回字符串 str 開頭連續(xù)包含字符串 accept 內(nèi)的字符數(shù)目。所以,如果 str 所包含的字符都屬于 accept,那么返回 str 的長度;如果 str 的第一個字符不屬于 accept,那么返回 0。
注意:檢索的字符是區(qū)分大小寫的。
提示:提示:函數(shù) 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; } |
執(zhí)行結(jié)果:
| 1 | str 前 3 個字符都屬于 accept |
C語言strcspn()函數(shù):計算字符串str中連續(xù)有幾個字符都不屬于字符串a(chǎn)ccept
頭文件:#inclued<string.h>
strcspn() 用來計算字符串 str 中連續(xù)有幾個字符都不屬于字符串 accept,其原型為:
| 1 | int strcspn(char *str, char *accept); |
【參數(shù)說明】str、accept為要進行查找的兩個字符串。
strcspn() 從字符串 str 的開頭計算連續(xù)的字符,而這些字符都完全不在字符串 accept 中。簡單地說,若 strcspn() 返回的數(shù)值為 n,則代表字符串 str 開頭連續(xù)有 n 個字符都不含字符串 accept 中的字符。
【返回值】返回字符串 str 開頭連續(xù)不含字符串 accept 內(nèi)的字符數(shù)目。
注意:如果 str 中的字符都沒有在 accept 中出現(xiàn),那么將返回 atr 的長度;檢索的字符是區(qū)分大小寫的。
提示:函數(shù) 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; } |
運行結(jié)果:
| 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; } |
運行結(jié)果:
| 1 | s1 is diffrent from s2! |
總結(jié)
以上是生活随笔為你收集整理的C语言中strspn()函数和strcspn()函数的对比使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使命召唤远射勋章怎么刷
- 下一篇: 输卵管堵塞表现是什么