Enhancement - caseless find

- Added support for a starting offset.
This commit is contained in:
Paul Beckingham 2010-01-27 09:50:10 -05:00
parent 2dfe144236
commit 06ecef76d3
3 changed files with 52 additions and 1 deletions

View file

@ -519,3 +519,50 @@ std::string::size_type find (
}
////////////////////////////////////////////////////////////////////////////////
std::string::size_type find (
const std::string& text,
const std::string& pattern,
std::string::size_type begin,
bool sensitive /*= true*/)
{
// Implement a sensitive find, which is really just a loop withing a loop,
// comparing lower-case versions of each character in turn.
if (!sensitive)
{
// Handle empty pattern.
const char* p = pattern.c_str ();
size_t len = pattern.length ();
if (len == 0)
return 0;
// Handle bad begin.
if (begin >= len)
return std::string::npos;
// Evaluate these once, for performance reasons.
const char* t = text.c_str ();
const char* start = t + begin;
const char* end = start + text.size ();
for (; t < end - len; ++t)
{
int diff;
for (size_t i = 0; i < len; ++i)
if ((diff = tolower (t[i]) - tolower (p[i])))
break;
// diff == 0 means there was no break from the loop, which only occurs
// when a difference is detected. Therefore, the loop terminated, and
// diff is zero.
if (diff == 0)
return t - start;
}
return std::string::npos;
}
// Otherwise, just use std::string::find.
return text.find (pattern, begin);
}
////////////////////////////////////////////////////////////////////////////////