boost字符串匹配算法简单示例

        字符串匹配算法常见的主要有KMP算法及Boyer-Moore算法,其原理详见:

               KMP:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

               Boyer-Moore:http://www.ruanyifeng.com/blog/2013/05/boyer-moore_string_search_algorithm.html

        Boost也提供了两种算法的实现,下面是一个简单的例子:

       

#include<boost\algorithm\searching\boyer_moore.hpp>
#include<boost\algorithm\searching\knuth_morris_pratt.hpp>
#include <iostream> 
int _tmain(int argc, _TCHAR* argv[])
{
	//----------------------------------boyer_moore字符匹配算法-------------
	std::string text("here is an simple example");
	std::string pattern("example");

	std::string::const_iterator it = boost::algorithm::boyer_moore_search<>(
             text.begin(), 
			 text.end(),
             pattern.begin(),
             pattern.end());

	assert(it != text.end());
    it = boost::algorithm::boyer_moore_search(text, pattern); 
	assert(it != text.end());
    it = boost::algorithm::boyer_moore_search<std::string, std::string>(text, "simple");
	assert(it != text.end());
    it = boost::algorithm::boyer_moore_search<std::string, std::string>(text, "hello");
	assert(it == text.end());

	//----------------------------------kmp字符匹配算法-------------
	it = boost::algorithm::knuth_morris_pratt_search<>(
         text.begin(), 
		 text.end(),
         pattern.begin(),
         pattern.end());
	assert(it != text.end());
    it = boost::algorithm::knuth_morris_pratt_search(text, pattern); 
	assert(it != text.end());
    it = boost::algorithm::knuth_morris_pratt_search<std::string, std::string>(text, "simple");
	assert(it != text.end());
    it = boost::algorithm::knuth_morris_pratt_search<std::string, std::string>(text, "hello");
	assert(it == text.end());
    return 0;
}



你可能感兴趣的:(KMP,boost,Boyer-Moore)