C 標準庫 – string.h之strspn使用

zhangrxiang發表於2019-05-10

strspn

  • Returns the length of the initial portion of str1 which consists only of characters that are part of str2.
  • The search does not include the terminating null-characters of either strings, but ends there.
  • 檢索字串 dest 中第一個不在字串 src 中出現的字元下標。返回 dest 所指向的空終止位元組串的最大起始段( span )長度,段僅由 src 所指向的空終止位元組字串中找到的字元組成。
  • 若 dest 或 src 不是指向空終止位元組字串的指標,則行為未定義。
size_t strspn( const char *dest, const char *src );

Parameters

dest

  • C string to be scanned.
  • 指向要分析的空終止位元組字串的指標

src

  • C string containing the characters to match.
  • 指向含有要搜尋的字元的空終止位元組字串的指標

Return value

  • The length of the initial portion of str1 containing only characters that appear in str2.Therefore, if all of the characters in str1 are in str2, the function returns the length of the entire str1 string, and if the first character in str1 is not in str2, the function returns zero.size_t is an unsigned integral type.
  • 僅由來自 src 所指向的空終止位元組字串的字元組成的最大起始段長度。
  • 該函式返回 dest 中第一個不在字串 src 中出現的字元下標。

Example

//
// Created by zhangrongxiang on 2018/2/5 17:28
// File strspn
//

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

//C 庫函式 size_t strspn(const char *str1, const char *str2) 檢索字串 str1 中第一個不在字串 str2 中出現的字元下標。

int main() {
    size_t len;
    const char str1[] = "ABCDEFG02018ABCDEFG02018";
    const char str2[] = "ABCD";
    const char str3[] = "2018";
    const char str4[] = "AB";
    const char str5[] = "AC";
    const char str6[] = "aC";
    len = strspn(str1, str2);
    printf("%d
", (unsigned int) len); //4
    len = strspn(str1, str3);
    printf("%d
", (unsigned int) len); //0
    len = strspn(str1, str4);
    printf("%d
", (unsigned int) len); //2
    len = strspn(str1, str5);
    printf("%d
", (unsigned int) len); //1
    len = strspn(str1, str6);
    printf("%d
", (unsigned int) len); //0

    char strtext[] = "129th";
    char cset[] = "1234567890";

    len = strspn(strtext, cset);
    printf("The initial number has %d digits.
", (int) len);//3

    const char *string = "abcde312$#@";
    const char *low_alpha = "qwertyuiopasdfghjklzxcvbnm";

    len = strspn(string, low_alpha);
    printf("%d
",(int)len);//5
    //After skipping initial lowercase letters from `abcde312$#@`
    printf("After skipping initial lowercase letters from `%s`
"
               "The remainder is `%s`
", string, string + len);//The remainder is `312$#@`

    return (0);
}

參考文章

轉載註明出處

相關文章