有没有一个好的方法来检查C++中的常见子字符串
Is there a good way to check for common substrings in C++?
我想从一个输入文件中找到一组与其他单词共享公共子字符串的单词。
因此,输入文件中的一个可能单词是:"area"与之比较的字符串是"-are-d"
有没有一种好的方法来比较和验证两个字符串是否都包含"are"子字符串?
您可以使用正则表达式。
这是你需要的代码:
#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_match
。如果要匹配子字符串,请使用regex_search
。在g++4.8.1中,您需要使用boost库,因为没有实现regex 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
相关文章:
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- C++如何在向量中查找最常见的元素
- Printf 命令不打印时添加了查找常见除数的新代码
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 打印二叉树中的常见元素
- 是否存在用于 C 或 C++ 中常见数学运算(例如最小值、最大值和平均值)的可导入库?
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- 如何从文本文件中查找最常见的字母和出现次数?
- 对类的未定义引用,常见答案尚未解决
- 查找字符串中最常见的字母
- 访问位域联合是C++标准中常见的初始数据未定义行为
- 抛出"bad_alloc"的最常见原因是什么?
- 拼接图像无法检测常见特征点
- Cppcheck 静态代码分析器实际上可以检测到不太常见的警告(如 "Relative Path Traversal (CWE-23)" 或"Buffer Under-read(CWE-127)")吗
- 模板对象的C 数组:施放到常见的非类型模板参数是UB吗?
- 如何将字符串保存在最长的常见子序列递归算法中
- DLL的常见记忆
- 在列表中找到最常见的元素(C STL)
- 为什么如果..如果..还有常见的范围?以及list的范围很常见
- #include 包含的头文件已包含的头文件是否常见?