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

How do you pattern match a string in a vector?

本文关键字:字符串 向量 模式匹配      更新时间:2023-10-16

我在向量中有数据,我需要看看它在第三个元素中是否有"买入"或"卖出"一词 vrecord[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] << " ";
    }

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

考虑到 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] = '';    
    if ( buff[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 );
}

在这种情况下,使用在标头<algorithm>中声明的标准算法std::find查找单词"Buy"很简单。例如

#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或基于范围的for循环。 例如

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];
                        } );