I needed this to work cross-platform and with non-standard character types (something I defined as XChar8). You need to pass the lengths of the source string and the substring you are searching for.
/*
Substring search when the string is not null-terminsted XChar8 array.
Arguments:
source - The source string to be searched
sourceLen - Length of the source string
find - the substring to be found
findLen - Length of the substring
Return value:
Pointer to the substring in the source, or NULL if not found.
*/
XChar8 *FindSubstring(XChar8 *source, size_t sourceLen, XChar8 *find, size_t findLen)
{
int found = 0;
size_t i, j;
XChar8 *s = NULL, *f = NULL;
if (sourceLen < findLen)
return NULL;
for (i = 0; i < sourceLen - findLen; i++)
{
s = source++;
f = find;
if (*f++ == *s++)
{
for (j = 0; j < findLen - 1; j++)
{
if (*f++ != *s++)
{
break;
}
}
if (j == findLen - 1)
{
found = 1;
break;
}
}
}
if (!found)
return NULL;
return s - findLen;
}
In case you need this to work for both: single and double byte encodings, you can call the function again, with a wide char string. Something like this:
XChar8 *findStr = NULL; XChar8 targetStr8[] = "someString"; wchar_t targetStr16[] = L"someString"; XChar8 *targetStr8 = targetStr8; XChar8 *targetStr16 = (XChar8 *) targetStr16;findStr =FindSubstring(buffer, bufferLen, targetStr8, sizeof(targetStr8) - 1);if (!findStr) { findStr = FindSubstring(buffer, bufferLen, targetStr16, sizeof(targetStr16) - 2); }