如何模式匹配向量中的字符串
How do you pattern match a string in a vector?
我在向量中有数据,我需要看看它在第三个元素中是否有"买入"或"卖出"一词 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::getline
或getline
和/或类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::count
、std::count_if
、std::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];
} );
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 在将字符串放入字符串向量时遇到问题?
- 如何从字符串向量构造对象并避免复制?
- 如何在目录及其子文件夹中构建文件名字符串向量?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 将字符串向量中的字符串放入主字符串中
- 如何在 c++ 中从字符串向量中读取
- 用字符串的向量分配字符串向量
- 如何使用 STL 算法将整数向量转换为字符串向量?
- C++ 中字符串向量的索引
- 如何根据第二列/第三列等对字符串向量进行排序?
- 如何从输入中获取字符串向量?
- 使用 C++-17,如何从字符串向量填充元组
- 对于循环增量器不能用作字符串向量的索引
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 如何从字符串向量中选择第 n 个位置?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 反转不带反转函数的字符串向量
- 如何在字符串向量中指向const int
- 如何在字符串向量中找到某个值