參考原文:https://blog.csdn.net/iot_change/article/details/8496977
find_first_of()這個函數用錯好幾次,所以記錄下來。記重點:
find_first_of 函數最容易出錯的地方是和find函數搞混。它最大的區別就是如果在一個字符串str1中查找另一個字符串str2,如果str1中含有str2中的任何字符,則就會查找成功,而find則不同;
一:find
函數原型:
size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;
參數說明:pos查找起始位置 n待查找字符串的前n個字符
使用樣例:
string str1("the usage of find can you use it");
string str2("the");
上面定義出了兩個字符串;
str1.find(str2); // 從串str1中查找時str2,返回str2中首個字符在str1中的地址
str1.find(str2,5); // 從str1的第5個字符開始查找str2
str1.find("usage"); // 如果usage在str1中查找到,返回u在str1中的位置
str1.find("o"); // 查找字符o並返回地址
str1.find("of big",2,2); // 從str1中的第二個字符開始查找of big的前兩個字符
二:find_first_of
函數原型:
size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char c, size_t pos = 0 ) const;
參數和find基本相同,不在贅述!
特別注意:
find_first_of 函數最容易出錯的地方是和find函數搞混。它最大的區別就是如果在一個字符串str1中查找另一個字符串str2,如果str1中含有str2中的任何字符,則就會查找成功,而find則不同;
比如:
string str1("I am change");
string str2("about");
int k=str1.find_first_of(str2); //k返回的值是about這5個字符中任何一個首次在str1中出現的位置;
//the usage of find /find_first_of by heat_nan from ZZULI
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1("Hi,every one! I am heat_nan from ZZULI. one");
string str2("heat_nan");
int k=str1.find(str2);
cout<<"The position of 'heat_nan' is "<<k<<endl;
int k1=str1.find("one");
cout<<"The postion of the first 'one' is "<<k1<<endl;
int k2=str1.find("one of",k1+1,3);
cout<<"The postion of the second 'one' is "<<k2<<endl;
int k3=str1.find_first_of("aeiou");//here k3=1
while(k3!=string::npos) //hint: here "string::npos"means find failed
{
str1[k3]='*';
k3=str1.find_first_of("aeiou",k3+1);
}
cout<<str1<<endl;
return 0;
}