std::strcspn

来自cppreference.com
< cpp‎ | string‎ | byte
在标头 <cstring> 定义
std::size_t strcspn( const char *dest, const char *src );

返回 dest 所指向的空终止字节字符串的最大起始段长度,该段只由 src 所指向的空终止字节字符串中找到的字符组成。

函数名代表“补集段 (complementary span)”。

参数

dest - 指向要分析的空终止字节字符串的指针
src - 指向含有要搜索字符的空终止字节字符串的指针

返回值

仅由 src 所指向的空终止字节字符串中找不到的字符组成的最大起始段长度。

示例

#include <cstddef>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <string>
 
int main()
{
    std::string s = "abcde312$#@";
    const char* invalid = "*$#";
 
    const std::size_t valid_len = std::strcspn(s.c_str(), invalid);
    if (valid_len != s.size())
    {
        std::cout << std::quoted(s)
                  << " 从位置 " << valid_len << " 开始包含无效字符\n"
                  << std::string(valid_len + 1, '-') << "^\n";
    }
}

输出:

"abcde312$#@" 从位置 8 开始包含无效字符
---------^

参阅

返回仅由另一字节字符串中找到的字符组成的最大起始段的长度
(函数)
返回仅由另一宽字符串中找到的宽字符组成的最大起始段的长度
(函数)
寻找任何来自分隔符集合的字符的首个位置
(函数)
寻找字符的首次出现
(std::basic_string<CharT,Traits,Allocator> 的公开成员函数)