Sting和vector的查找和刪除

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表示子串長度。

     

       

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章