Introduction
There is no C library function to find the first occurrence of a word in a string
. When using strstr()
, a code defect occurs when the match finds a value that is not in a complete word.
Using the Code
Link with shlwapi.lib to get StrStrI()
:
In header
#define IN
#define OPTIONAL
#include <windows.h>
#include <shlwapi.h>
char * StrStrWord
( IN char *pcSearched
, IN const char *pcWordToFind
, IN const size_t nSearchedSize
, OPTIONAL IN int bUseCase = 1
, OPTIONAL IN char *pcWordChars = NULL);
In C++ module
char * StrStrWord
(IN char *pcSearched
, IN const char *pcWordToFind
, IN const size_t nSearchedSize
, OPTIONAL IN int bUseCase , OPTIONAL IN char *pcWordChars ) {
static const char acWord[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
if (!pcSearched || !pcWordToFind)
return NULL;
size_t nLenSearchStr = strnlen(pcWordToFind, nSearchedSize);
size_t nLenWordStr = strnlen(pcWordToFind, nSearchedSize);
if (nSearchedSize < nLenSearchStr)
return NULL;
const char *pcCharsInWord;
if (pcWordChars == NULL)
pcCharsInWord = acWord;
else
pcCharsInWord = pcWordChars;
if (bUseCase) {
for (char *pc = strstr(pcSearched, pcWordToFind)
; pc
; pc = strstr(pc + 1, pcWordToFind))
{
const char *pcSepEnd = strchr(pcCharsInWord, pc[nLenWordStr]);
if (!pcSepEnd) {
if (pc == pcSearched)
return pc;
const char *pcSepStart = strchr(pcCharsInWord, pc[-1]);
if (!pcSepStart)
return pc;
}
}
}
else {
for (char *pc = StrStrI(pcSearched, pcWordToFind)
; pc
; pc = StrStrI(pc + 1, pcWordToFind))
{
const char *pcSepEnd = strchr(pcCharsInWord, pc[nLenWordStr]);
if (!pcSepEnd) {
if (pc == pcSearched)
return pc;
const char *pcSepStart = strchr(pcCharsInWord, pc[-1]);
if (!pcSepStart)
return pc;<br /> }
}
}
return NULL;
}
History
- 14th March, 2014: Initial version