簡體   English   中英

C ++字符串迭代器“先找到”

[英]c++ string iterator “find first of”

字符串迭代器中是否有類似於string上的find_first_of的方法? 就像是:

string::iterator it;
string str("  h asdasf ^& saafa");
it = FIND_FIRST_OF("&az^");
std::cout << *it << std::endl;

結果:

一種

您可以間接做到

auto pos = str.find_first_of("&az^");

然后推進迭代器

if(pos != std::string::npos) // thanks to @Mike Seymour
    std::advance(it, pos);

我想您也std::find使用lambda來執行某種std::find ,但以上內容實際上更加簡單明了。

我認為std::find_first_of是您想要的。

string::iterator it;
string str("  h asdasf ^& saafa");
string find_me ("&az^");
it = std::find_first_of (str.begin(), str.end(), find_me.begin(), find_me.end());
std::cout << *it << std::endl;

如果以任何頻率使用此方法,我將編寫一個函數來清理構造/使用中間find_me變量所涉及的開銷。

嘗試這個:

std::string::size_type position = example.find_first_of(".");
if (position != std::string::npos)
{
  std::advance(string_iterator, position);
}
else
{
  string_iterator = example.end();
}

std::string與其他查找方法不同,它具有自己的方法find_first_offind_last_of

這是一個示范節目

#include <iostream>
#include <string>

int main() 
{
    std::string s( "  h asdasf ^& saafa" );
    auto pos = s.find_first_of( "&az^" );

    if ( pos != std::string::npos ) std::cout << s[pos] << std::endl;

    pos = s.find_last_of( "&az^" );

    if ( pos != std::string::npos ) std::cout << s[pos] << std::endl;

    return 0;
}

程序輸出為

a
a

這是另一個演示程序,該程序查找字符文字中指定的字符串中的所有字符

#include <iostream>
#include <string>

int main() 
{
    std::string s( "  h asdasf ^& saafa" );

    for ( std::string::size_type pos = 0; 
          ( pos = s.find_first_of( "&az^", pos ) ) != std::string::npos;
          ++pos )
    {
        std::cout << pos << ": " << s[pos] << std::endl;
    }        

    return 0;
}

程序輸出為

4: a
7: a
11: ^
12: &
15: a
16: a
18: a

知道找到的位置,您總是可以在對象中獲得相應的迭代器:

std::string::iterator it = std::next( s.begin(), pos );

要么

auto it = std::next( s.begin(), pos );

或簡單地

std::string::iterator it = s.begin() + pos;

在頭文件<algorithm>中聲明了標准算法std::find_first_of ,該<algorithm>也可以與std :: string類型的對象一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM