如何使String::Find(is)省略此项
How to make String::Find(is) omit this
如果我有一个列表,其中包含4个节点("this";"test example";"有点像";"a small"),并且我想找到每个具有"is"的字符串(该列表只有1个正)。这个话题已经被发布了很多次,我用这些来帮助我走到这一步。然而,我看不出我是如何从一个积极的结果中省略"这个"的。我可能会使用string::c_str,然后在缩减了更大的列表后自己找到它。或者有没有一种方法可以使用字符串::find_first_of?看来还有更好的办法。谢谢
编辑:我知道我可以省略一个特定的字符串,但我正在寻找更大的图片b/c我的列表相当大(例如:诗歌)。
for(it = phrases.begin(); it != phrases.end(); ++it)
{
found = it->find(look);
if(found != string::npos)
cout << i++ << ". " << *it << endl;
else
{
i++;
insert++;
}
}
只是想澄清一下:你在为什么而挣扎?
你想做的是检查你所发现的是一个单词(或短语)的开头还是单词(或词组)的结尾
即。检查是否:
found
等于phrases.begin
或者found
之前的元素是空间- 与
found
之后的两个元素为空间ORphrases.end
编辑:您可以使用found
访问找到的字符(将X替换为您正在查找的字符串的长度(look.length)
found = it->find(look);
if(found!=string::npos)
{
if((found==0 || it->at(found-1)==' ')
&& (found==it->length-X || it->at(found+X)==' '))
{
// Actually found it
}
} else {
// Do whatever
}
我们可以使用boost正则表达式来搜索正则表达式。下面是一个示例代码。使用正则表达式可以创建复杂的seacrh模式。
#include <boost/regex.hpp>
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
using namespace boost;
using namespace std;
int main()
{
std::string list[4] = {"this","hi how r u ","is this fun is","no"};
regex ex("^is");
for(int x =0;x<4;++x)
{
string::const_iterator start, end;
boost::char_separator<char> sep(" ");
boost::tokenizer<boost::char_separator<char> > token(list[x],sep);
cout << "Search string: " << list[x] <<"n"<< endl;
int x = 0;
for(boost::tokenizer<boost::char_separator<char> >::iterator itr = token.begin();
itr!=token.end();++itr)
{
start = (*itr).begin();
end = (*itr).end();
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
if(boost::regex_search(start, end, what, ex, flags))
{
++x;
cout << "Found--> " << what.str() << endl;
}
}
cout<<"found pattern "<<x <<" times."<<endl<<endl;
}
return 0;
}
输出:
搜索字符串:此
找到模式0次。
搜索字符串:你好r u
找到模式0次。
搜索字符串:这是有趣的
已找到->已找到->被发现模式2次。
搜索字符串:无
找到模式0次。
我没有意识到你只想匹配"is"。您可以使用std::istringstream为您标记它:
std::string term("is");
for(std::list<std::string>::const_iterator it = phrases.begin();
it != phrases.end(); ++it)
{
std::istringstream ss(*it);
std::string token;
while(ss >> token)
{
if(token == term)
std::cout << "Found " << token << "n";
}
}
相关文章:
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- std::vector的包装器,使数组的结构看起来像结构的数组
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何在全屏模式下(在OpenGL中)使背景透明
- cppcheck在const std::string[]上引发警告
- 找到两对数字,使它们的乘积的绝对差最小化
- 如何使g++不区分<string>和<string.h>
- 在 C++ 中转换 std::string,使其可以是 C# 中的 byte[]
- std::u8string与std::string有何不同?
- 为什么std :: string使wsagetlasterror返回零
- 可以std::string reconfiguration使指向堆的指针无效
- 如何使String::Find(is)省略此项
- std::string在与unordered_sets一起使用时是否需要哈希函数
- 将regex_search与std::string一起使用时的无限循环
- 为什么我不能使类内初始化的"const const std::string"成为静态成员
- 如何使助推unordered_map支持蝇量级<string>
- 如何迭代std::string中所有匹配的正则表达式,使其在c++11 std::regex中的起始位置
- string作为数组使用时打印超出限制的字符
- C++11编译器何时会使RVO和NRVO优于移动语义和常量引用绑定
- 是否可以使std::string始终包含一个小写字符串