strcspn

文字列中の指定文字列を含まない先頭部分の長さを求めます.

#include <string.h>
size_t strcspn(
    const char *s1,
    const char *s2
);

strcspn 関数は s1 が指す文字列の中で,s2 が指す文字列の中の文字以外から構成される先頭部分の最大の長さを計算します.

戻り値

  • 先頭部分の長さ

C言語サンプルプログラム

strcspn 関数を使用して文字列中から指定文字列を含まない先頭部分の長さを求めるサンプルプログラムを以下に示します.

/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* main */
int main(void) {
    char s1[] = "Joe Cool";
    char s2[] = "o";
    char s3[] = "cC";
    size_t n;

    n = strcspn(s1, s2);
    printf("%s 中から %s が見つかるまでの長さ: %d\n", s1, s2, n);

    n = strcspn(s1, s3);
    printf("%s 中から %s が見つかるまでの長さ: %d\n", s1, s3, n);

    return EXIT_SUCCESS;
}

実行例

サンプルプログラムの実行結果は以下のようになります.

Joe Cool 中から o が見つかるまでの長さ: 1
Joe Cool 中から cC が見つかるまでの長さ: 4