1、String类支持一套查找函数,都以find的各种变化形式命名(6.8),find()是最简单的实例。在一个String中查找某个字符串首次出现的位置,使用find_first_of 内置函数。示例如下:
string str=("The expense of spirit!");
int length=str.size();
string::size_type pos=0;
pos=str.find_first_of(' ',pos);
string::size_type pos2 = name.find( "Anna" );
find_first_of用于在str中从pos位置开始查找第一次出现空格的位置。
此外还有find()系列的函数:find_first_not_of(),find_last_of(),find_last_not_of(),rfind();
2、查找vector中的某个元素
vector<string> vec(2);
vec.push_back("hello");
vec.push_bach("world");
vector<string>:iterator it;
string search_value=("world");
it=find(vec.begin(),vec.end(),search_value);
it返回的是迭代器,如果想返回位置的int值,我自己写了个函数如下:
int find_ranking(string boys,vector<string> girl_list){
for(unsigned int i=1;i<201;i++){
if (girl_list[i]==boys){
return i;
}
}
return -1;
}
3、在Sting中提取子串。使用substr()函数
string::size_type pos = 4 prev_pos = 2;
string temp=("hello world");
string sub= temp.substr(prev_pos,pos-pre_pos);
re_pos指向子串第一个字符的位置,pos指向子串最后一个字符的下一个位置,pos-pre_pos表示子串长度。