3
\$\begingroup\$

I am implementing a function which searches through a ring queue for a given substring. The function returns true if the substring is found, otherwise false. There is a cell containing null between the tail and head to signify the end of string. Please give feedback on this implementation.

bool SoftwareSerial::contains(const char *substr){
 char *pBuffer =_receive_buffer + _receive_buffer_head; 
 char *pSubstr = substr;
 for(; *pBuffer != 0 && *pSubstr != 0; ++pBuffer ){
 if(pBuffer == (_receive_buffer + _SS_MAX_RX_BUFF)){
 pBuffer = _receive_buffer + _receive_buffer_head;
 }
 if(*pBuffer != *pSubstr){
 pSubstr = substr;
 continue;
 }
 ++pSubstr;
 }
 return (*pSubstr == 0);
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 18, 2015 at 20:00
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

There were few bugs in the function. 1. pStr should point to the start of the buffer once it reaches the end of the buffer. 2. A flag should be set when a character matches and unset the flag when next coming character doesn't match. Here the modified version that I believe is correct:

bool Buffer::contains(const char *pcSubstr){
const char *pcCurrentSubstr = pcSubstr;
const char *pStr = buffer + head;
bool seen = false;
for (; *pStr != 0 && *pcCurrentSubstr != 0; ++pStr){
 if(pStr == (buffer + MAX_BUFFER_SIZE)){
 pStr = buffer;
 }
 if(*pStr != *pcCurrentSubstr){
 pcCurrentSubstr = pcSubstr;
 if(seen){
 --pStr;
 }
 seen = false;
 continue;
 }
 seen = true;
 ++pcCurrentSubstr;
}
return (*pcCurrentSubstr == 0);
}
answered Mar 23, 2015 at 17:48
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.