C庫函數strcspn()計算兩個字符串中第一次出現的字符之前的字符數長度。句法:
strcspn(const char *str1, const char *str2) 參數: str1 :The Target string in which search has to be made. str2 :Argument string containing characters to match in target string. 返回值: 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 <stdio.h>
#include <string.h>
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 <stdio.h>
#include <stdlib.h>
#include <string.h>
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++ strcspn()用法及代碼示例
- Java HijrahDate getEra()用法及代碼示例
- Java HijrahDate getChronology()用法及代碼示例
- Java HijrahDate equals()用法及代碼示例
- Java HijrahDate atTime()用法及代碼示例
- Java HijrahChronology range()用法及代碼示例
- Java HijrahChronology zonedDateTime(TemporalAccessor)用法及代碼示例
注:本文由純淨天空篩選整理自Vaishnavi tripathi大神的英文原創作品 strcspn() in C。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。