문자열 검색으로 strstr 사용 시, 고려 및 주의 점

2023. 5. 18. 20:152018년 이전 관심사/프로그램 언어

반응형

문제

변수에 0x00으로 채워져 있고, 중간에 문자열이 있는 경우

{0x00, 0x00, 0x00, 'T', 'E', 'S', 'T', 0x00, 0x00}

 

중간 문자열의 위치를 찾기 위해 strstr 함수를 사용 했다.

 

이때 문제는 변수 처음에 0x00이 있기 때문에 strstr 함수에서는 TEST 문자를 찾기 전에 문자 끝으로 인식하여

NULL를 리턴 한다.

 

해결 방법

 

이를 해결 하기 위해 아래와 같은 커스텀 함수를 만들어서 사용 함.

uint8_t *custom_str_str(const uint8_t *p_str, const uint8_t *p_strSearch, uint32_t length)
{
    const uint8_t *p_pos, *p_find_pos;

    if (*p_strSearch == 0)
    {
        return (uint8_t*)p_str;
    }

    while(length > 0)
    {
        if(*p_str == *p_strSearch)
        {
            p_pos = p_str + 1;
            p_find_pos = p_strSearch + 1;
            while (*p_find_pos != 0 && *p_pos != 0 && *p_pos == *p_find_pos)
            {
                p_pos++;
                p_find_pos++;
            }

            if(*p_find_pos == 0)
            {
                return (uint8_t*)p_str;
            }

            if(*p_pos == 0)
                break;
        }

        p_str++;
        length--;
    }

    return (uint8_t*) NULL;
}

 

        memset(tempDfBuffer, 0x00, sizeof(tempDfBuffer));
        DF_Read(nDFLastPage, 0, (uint8_t*)tempDfBuffer, nDFLastPageDataLen);

        pStrPtr = custom_str_str(tempDfBuffer, (const uint8_t *)"HDRC-EXT", sizeof(tempDfBuffer));

        if( pStrPtr != NULL )
        {
            strncpy((char*)buff_DataFlash, (char*)pStrPtr, sizeof(buff_DataFlash));
        }
반응형