字符串匹配实现
String matching implementation
我写了下面的代码来检查文本中是否存在certin字符串。问题是即使文本中存在模式,match()
函数也总是返回false
。
int main(){
char *text="hello my name is plapla";
char *patt="my";
cout<<match(patt,text);
system("pause");
return 0;
}
bool match(char* patt,char* text){
int textLoc=0, pattLoc=0, textStart=0;
while(textLoc <= (int) strlen(text) && pattLoc <= (int)strlen(patt)){
if( *(patt+pattLoc) == *(text+textLoc) ){
textLoc= textLoc+1;
pattLoc= pattLoc+1;
}
else{
textStart=textStart+1;
textLoc=textStart;
pattLoc=0;
}
}
if(pattLoc > (int) strlen(patt))
return true;
else return false;
}
在while
循环中尝试pattLoc < (int)strlen(patt)
。循环将在pattLoc == 2
时停止,因此避免将"my"
的' '
与"hello my name is pala"
的' '
进行比较,后者将pattloc
设置为0
和return false
。
或者最好使用字符串substr
。
显而易见的解决方案是:
bool
match( std::string const& pattern, std::string const& text )
{
return std::search( text.begin(), text.end(),
pattern.begin(), pattern.end() )
!= text.end();
}
这是惯用的C++,也是我所期望的任何C++程序员至少在专业环境下写。
如果目标是学习如何编写这样的函数,那么,以上并不是一个很好的解决方案。那么解决方案应该是mroe分而治之;match
太多了,你放不下在一个功能中。我推荐这样的东西:
bool
startsWith( std::string::const_iterator begin,
std::string::const_iterator end,
std::string const& pattern )
{
return end - begin >= pattern.size()
&& std::equal( pattern.begin(), pattern.end(), begin );
}
bool
match( std::string const& pattern, std::string const& text )
{
std::string::const_iterator current = text.begin();
while ( current != text.end()
&& !startsWith( begin, text.end(), pattern ) ) {
++ current;
}
return current != text.end();
}
这显然是可以改进的;例如当剩余文本的长度为小于图案的长度。
如果你的教授坚持你使用char const*
(如果他坚持在char*
上,那么他完全不称职,应该被解雇)可以很容易地重写:只需将对begin
的所有调用替换为指针以及对具有pointer + strlen(pointer)
的end
的所有调用。
我已经解决了问题:
while(textLoc <= (int) strlen(text) && pattLoc <= (int)strlen(patt))
应该是:
while(textLoc < (int) strlen(text) && pattLoc < (int)strlen(patt))
以及if(pattLoc > (int) strlen(patt))
到if(pattLoc >= (int) strlen(patt))
- 如果没有malloc,链表实现将失败
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- Arduino上的串行和流之间有什么区别,以及如何实现序列
- 如何实现将前缀与字符串匹配的最快算法
- 可以视觉C 检查不匹配的原型和实现
- 为什么我的函数调用与此泛型函数实现不匹配?
- 我应该用什么来实现c++中的加权二分匹配算法
- 串行代码的并行MPI实现
- 使用后缀数组和 LCP(-LR) 实现字符串模式匹配
- C++ openmp 比串行实现慢得多
- 实现派生类构造函数时出错:"重载函数的任何实例都与指定的类型匹配
- 字符串匹配算法的c++实现
- 如何使用标准库(包括boost)实现简单的字符串模式匹配
- 字符串匹配实现
- 在msgpack的c++实现中,如何在使用pack_map或pack_array对对象进行串行化后将其反串行化
- 用c++实现pc机与arduino之间的RS232串行通信
- 使用矢量实现串行缓冲区的最佳方法是什么<char>?
- WebSocket服务器实现(接受密钥不匹配)