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);
}
\$\endgroup\$
0
0
\$\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);
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.