C++标准库std::string的find_first_not_of 方法介绍:

发布时间 2023-12-21 16:46:25作者: He_LiangLiang

C++标准库 std::string  的  find_first_not_of 方法介绍:

 

例如:

stra.find_first_not_of(s_fmt_a)
在字符串  stra 中找到第一个 不在 s_fmt_a 字符串中出现过的字符。
stra = "abc", abc 字符 都在 s_fmt_a 字符串里面出现过,所以第一个不在s_fmt_a里的字符是找不到的,
返回的结果是 std::string::npos;

这里有点绕:

再举例:

strf 是 "abcde-c-d"。
在strf 中找第一个不在 s_fmt_a 字符串里面出现过的字符,我们找到了"-",
"-"字符串 不在 s_fmt_a 字符串的范围里面,而且是第一个出现,所以返回了它的下标位置5.

 

std::string::find_first_not_of 是 C++ 标准库中的一个成员函数,

用于在字符串中查找第一个不包含在指定字符集中的字符的位置。


比如:strg.find_first_not_of(s_fmt_a)

  就是找 strg 字符串中,第一个不包含在 s_fmt_a 字符集里面的字符。这个字符是"_",位置是3.

 

 

#include <iostream>
#include <string>

int main(){
    std::string  stra = "abc";
    std::string  strb = "1234";
    std::string  strc = "123abc";
    std::string  strd = "ABCdef123";
    std::string  stre = "aabbcc.0.0";
    std::string  strf = "abcde-c-d";
    std::string  strg = "abc_d_e_f..1233";
    std::string  strh = "#abc_D_-E_f..1233";

    std::string s_fmt_a = "abcdefghijklmnopqrstuvwxyz.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std::string s_fmt_b = "_";
    std::string s_fmt_c = "-";
    std::string s_fmt_d = "1234567890";
    std::string s_fmt_e = ".";

    size_t f1 = stra.find_first_not_of(s_fmt_a);
    if(f1 == std::string::npos){
        std::cout <<"stra NOT find"<< std::endl;
    }
    else {
        std::cout << "stra find at:" << f1 <<std::endl;
    }

    size_t f2 = strd.find_first_not_of(s_fmt_a);
    if(f2 == std::string::npos){
        std::cout <<"strd NOT find"<< std::endl;
    }
    else {
        std::cout << "strd find at:" << f2 <<std::endl;
    }

    size_t f3 = stre.find_first_not_of(s_fmt_a);
    if(f3 == std::string::npos){
        std::cout <<"stre NOT find"<< std::endl;
    }
    else {
        std::cout << "stre find at:" << f3 <<std::endl;
    }

    size_t f4 = strf.find_first_not_of(s_fmt_a);
    if(f4 == std::string::npos){
        std::cout <<"strf NOT find"<< std::endl;
    }
    else {
        std::cout << "strf find at:" << f4 <<std::endl;
    }

    size_t f5 = strg.find_first_not_of(s_fmt_a);
    if(f5 == std::string::npos){
        std::cout <<"strg NOT find"<< std::endl;
    }
    else {
        std::cout << "strg find at:" << f5 <<std::endl;
    }

    size_t f6 = strh.find_first_not_of(s_fmt_a);
    if(f6 == std::string::npos){
        std::cout <<"strh NOT find"<< std::endl;
    }
    else {
        std::cout << "strh find at:" << f6 <<std::endl;
    }return 0;
}

// g++ helloa.cpp --std=c++11 -o a1.bin

 

stra NOT find
strd NOT find
stre NOT find
strf find at:5
strg find at:3
strh find at:0