【发布时间】:2014-04-30 01:58:30
【问题描述】:
我希望从输入文件中找到一组与其他单词共享公共子字符串的单词。
所以输入文件中可能出现的单词是:“area” 与之比较的字符串是“-are--d”
有没有比较好的方法来比较和验证两个字符串都包含“are”子字符串?
【问题讨论】:
标签: c++ string function comparison substring
我希望从输入文件中找到一组与其他单词共享公共子字符串的单词。
所以输入文件中可能出现的单词是:“area” 与之比较的字符串是“-are--d”
有没有比较好的方法来比较和验证两个字符串都包含“are”子字符串?
【问题讨论】:
标签: c++ string function comparison substring
您可以使用正则表达式。
这是您需要的代码:
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
int main()
{
std::string txt="-are--d";
std::tr1::regex rx("are");
bool matchFound = regex_search(txt.begin(), txt.end(), rx);
if(matchFound)
{
std::cout << "match found!";
}
}
【讨论】:
<regex>。事实上,它们自 2007 年以来一直是 TR1 库扩展。
如果您想匹配整个字符串,请使用regex_match。如果要匹配子字符串,请使用 regex_search。在 g++ 4.8.1 中,您需要使用 boost 库,因为未实现正则表达式 c++11。在 g++ 4.8.1 中,您可以使用以下代码编译代码:g++ regex_boost.cpp -o regex_boost -lboost_regex
#include <iostream>
#include <string>
#include <boost/regex.hpp>
//#include <regex> // it is not implemented in g++ 4.8.1
using boost::regex;
using boost::regex_match;
using boost::regex_search;
using namespace std;
int main() {
string fnames[] = {"fileone.txt", "data.txt", "pp.txt", "foo.out"};
regex txt_regex("[a-z]+\\.txt");
for (int i=0; i<4; ++i)
cout << fnames[i] << ":" << regex_match(fnames[i],txt_regex) << '\n';
string txt="-are-arde-dsarefdd";
regex rx("are");
// not matching because it should match the whole string
cout << txt << ":" << regex_match(txt, rx) << endl;
// matching substrings ("are" is matched)
cout << txt << ":" << regex_search(txt, rx) << endl;
return 0;
}
这个程序给出结果:
$ ./regex_boost
fileone.txt:1
data.txt:1
pp.txt:1
foo.out:0
-are-arde-dsarefdd:0
-are-arde-dsarefdd:1
【讨论】: