有没有一个好的方法来检查C++中的常见子字符串

Is there a good way to check for common substrings in C++?

本文关键字:C++ 常见 字符串 检查 有一个 方法      更新时间:2023-10-16

我想从一个输入文件中找到一组与其他单词共享公共子字符串的单词。

因此,输入文件中的一个可能单词是:"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