📜  C中的strcspn()

📅  最后修改于: 2021-05-26 00:43:41             🧑  作者: Mango

C库函数strcspn()计算两个字符串第一次出现的字符之前的字符数长度。
句法 :

strcspn(const char *str1, const char *str2)

Parameters:
str1 : The Target string in which search has to be made.
str2 : Argument string containing characters
to match in target string.

Return Value:
This function returns the number of characters before the 1st occurrence
of character present in both the string.
// C code to demonstrate the working of
// strcspn()
#include 
#include 
  
int main()
{
  
    int size;
  
    // initializing strings
    char str1[] = "geeksforgeeks";
    char str2[] = "kfc";
  
    // using strcspn() to calculate initial chars
    // before 1st matching chars.
    // returns 3
    size = strcspn(str1, str2);
  
    printf("The unmatched characters before first matched character :  %d\n", size);
}

输出:

The unmatched characters before first matched character :  3

实际应用:可以有此函数的许多实际应用,无论是文字游戏或不规则计算器。本文演示了一个简单的文字游戏。

规则:根据该游戏,有2位玩家参加比赛,其中1位玩家最初生成了一个字符串,并被要求生成一个字符串,该字符串具有许多不匹配的字符。 1回合后,玩家产生的字符串最多且不匹配的字符获胜。

// C code to demonstrate the application of
// strcspn()
  
#include 
#include 
#include 
  
int main()
{
  
    int score1 = 0, score2 = 0, k = 0, sizen = 0, size = 0;
  
    // initial Round1 strings
    char player1[] = "geeks";
    char play2[] = "";
  
    while (1) {
        // generating random character
        char randoml = 'a' + (random() % 26);
        play2[k++] = randoml;
  
        size = strcspn(play2, player1);
  
        if (size == sizen) {
            // if the character is present, break
            score2 = size;
            break;
        }
        else {
            sizen = size;
        }
    }
  
    // initial Round2 strings
    const char player2[] = "geeks";
    char play1[] = "";
    k = 0, sizen = 0;
  
    while (1) {
        // generating random character
        char randoml = 'a' + (random() % 26);
        play1[k++] = randoml;
  
        size = strcspn(play1, player2);
  
        if (size == sizen) {
  
            // if the character is present, break
            score1 = size;
            break;
        }
        else {
            sizen = size;
        }
    }
  
    if (score1 > score2)
        printf("Player 1 won!! Score : %d", score1);
    else if (score2 > score1)
        printf("Player 2 won!! Score : %d", score2);
    else
        printf("Match Drawn!! Score : %d", score1);
}

输出:

Match Drawn!! Score : 2
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。