C / C++中的strcspn()函数将两个字符串作为输入,即string_1和string_2作为其参数,并通过遍历string_2中存在的任何字符来搜索string_1。如果在string_1中找不到string_2的任何字符,则该函数将返回string_1的长度。此函数在cstring头文件中定义。
句法 :
size_t strcspn ( const char *string_1, const char *string_2 )
参数:该函数接受两个强制性参数,如下所述:
- string_1:指定要搜索的字符串
- string_2:指定包含要匹配字符的字符串
返回值:该函数返回字符之前任何从STRING_2匹配字符的STRING_1中走过的数量。
下面的程序说明了上述函数:
程序1:
// C++ program to illustrate the
// strcspn() function
#include
using namespace std;
int main()
{
// String to be travered
char string_1[] = "geekforgeeks456";
// Search these characters in string_1
char string_2[] = "123456789";
// function strcspn() traverse the string_1
// and search the characters of string_2
size_t match = strcspn(string_1, string_2);
// if matched return the position number
if (match < strlen(string_1))
cout << "The number of characters before"
<< "the matched character are " << match;
else
cout << string_1 <<
" didn't matched any character from string_2 ";
return 0;
}
输出:
The number of characters beforethe matched character are 12
程式2:
// C++ program to illustrate the
// strcspn() function When the string
// containing the character to be
// matched is empty
#include
using namespace std;
int main()
{
// String to be travered
char string_1[] = "geekforgeeks456";
// Search these characters in string_1
char string_2[] = ""; // Empty
// function strcspn() traverse the string_1
// and search the characters of string_2
size_t match = strcspn(string_1, string_2);
// if matched return the position number
if (match < strlen(string_1))
cout << "The number of character before"
<< "the matched character are " << match;
else
cout << string_1 <<
" didn't matched any character from string_2 ";
return 0;
}
输出:
geekforgeeks456 didn't matched any character from string_2
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。