你如何模式匹配向量中的字符串?

时间:2014-11-22 09:00:40

标签: c++ regex vector

我有一个向量中的数据,我需要看看它是否在第3个元素vrecord中有单词Buy或Sell [2]

在向量中查找字符串出现的最直接方法是什么?

数据:

198397685
2014-11-14 15:10:13
Buy
0.00517290
0.00100000
0.00100000
0.00000517
198398295
2014-11-14 15:11:14
Buy
0.00517290
0.00100000
0.00100000
0.00000517
203440061
2014-11-21 16:13:13
Sell
0.00825550
0.00100000
0.00100000
0.00000826

代码:

    vector<std::string> vrecords;
    while(std::fgets(buff, sizeof buff, fp) != NULL){
            vrecords.push_back(buff);
    }

    for(int t = 0; t < vrecords.size(); ++t){
            cout << vrecords[t] << " ";
    }

1 个答案:

答案 0 :(得分:2)

首先,在C ++中使用C i / o系统是个坏主意。最好使用C ++函数std::getline或类getline的成员函数get和/或std::basic_istream

考虑到C函数fgets还存储字符串中的新行字符。你应该删除它。例如

while ( std::fgets( buff, sizeof buff, fp ) != NULL )
{
    size_t n = std::strlen( buff );
    if ( n && buff[n-1] == '\n' ) buff[n-1] = '\0';    
    if ( buff[0] != '\0' ) vrecords.push_back( buff );
}

如果向量声明为std::vector<std::string>(我希望它没有被声明为例如std::vector<char *>),那么你可以改为编写

std::string record;
while ( std::getline( YourFileStream, record ) )
{
    if ( !record.empty() ) vrecords.push_back( record );
}

在这种情况下,找到&#34;购买&#34;使用标头std::find中声明的标准算法<algorithm>很简单。例如

#include <algorithm>
#include <iterator>

//...

auto it = std::find( vrecords.begin(), vrecords.end(), "Buy" );

if ( it != vrecords.end() ) 
{
    std::cout << "Word \"" << "Buy"
              << "\" is found at position " 
              << std::distance( vrecords.begin(), it )
              << std::endl;  
}

如果您需要找到以下任何单词买或卖,那么您可以使用标准算法std::find_first_of。例如

#include <algorithm>
#include <iterator>

//...

const char * s[] = { "Buy", "Sell" };

auto it = std::find_first_of( vrecords.begin(), vrecords.end(), 
                              std::begin( s ), std::end( s ) );

if ( it != vrecords.end() ) 
{
    std::cout << "One of the words \"" << "Buy and Sell"
              << "\" is found at position " 
              << std::distance( vrecords.begin(), it )
              << std::endl;  
}

如果您需要计算向量中有多少这样的单词,那么您可以在循环中使用上述方法或使用标准算法std::countstd::count_ifstd::accumulate或基于循环的范围。  例如

const char * s[] = { "Buy", "Sell" };

auto n = std::count_if( vrecords.begin(), vrecords.end(),
                        [&]( const std::string &record )
                        { 
                            return record == s[0] || record == s[1];
                        } );
相关问题