C++的一些快捷函数2----find

1、find_first_of

如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同;

例如:word = "qwer" ;  yuan ="aueio" ;int index = word.find_first_of(yuan, x);  则index=2 x指的是从下表为x的开始查找

2、find_first_not_of(const string &str,size_type index =0 ,size_type num)

返回在字符串中首次出现的不匹配str中的任何一个字符的首字符索引, 从index开始搜索, 如果全部匹配则返回string::npos

从index开始起搜索当前字符串, 查找其中与str前num个字符中的任意一个都不匹配的序列, 返回满足条件的第一个字符索引, 否则返回string::npos。

3、sprintf

//把整数123 打印成一个字符串保存在s 中。
例如:sprintf(s, "%d", 123); //产生"123"

           char s[8];  sprintf(s, "%d", i);

4、string::npos

string:npos是个特殊值,说明查找没有匹配

例如:查找字符串a是否包含子串b,strA.find(strB) != string:npos

str.find("哦")==string::npos时则说明字符串str中不存在“哦”这个字符

str.find("哦")!=string::npos则说明字符串str中存在“哦”这个字符

5、rfind(const string& str, size_t pos = npos) const noexcept;

从源字符串起始位置pos(默认为npos)处,查找有目标字符串str(string型字符串)的位置

例如:size_t found2 = str1.rfind("two"); if (found2 != string::npos) { str1.replace(found2, strlen("two"), "TWO"); } cout<<str1<<endl;

6、 find_last_of (const string& str, size_t pos = npos) const noexcept;

从源字符串起始位置pos(默认为npos)处,依此查找每个字符。如果某字符在目标字符串str(string型字符串)中,则返回首次匹配的该字符的位置。

例如:string str1("abcd efgh ijkl mnop qrst uvwx yz");  string str2("aeimqu");

size_t found1 = str1.find_last_of(str2);

while (found1 != string::npos) { str1[found1]='*'; found1 = str1.find_last_of(str2, found1-1); } cout<<str1<<endl;

7、find_last_not_of (const string& str, size_t pos = npos) const noexcept;

从源字符串起始位置pos(默认为npos)处,依此查找每个字符。如果某字符不在目标字符串str(string型字符串)中,则返回首次不匹配的该字符的位置。

例如:string str1("abcd efgh ijkl mnop qrst uvwx yz");string str2("bcd fgh jkl nop rst vwx yz *");

size_t found1 = str1.find_last_not_of(str2);

while (found1 != string::npos) { str1[found1]='*'; found1 = str1.find_last_not_of(str2, found1-1); } cout<<str1<<endl;

 

posted @ 2020-10-16 20:27  吉吉的奥利奥  阅读(516)  评论(0编辑  收藏  举报