Sign in to follow this  
BeanDog

Limit string::find() to only search first n chars? [Solved]

Recommended Posts

I'm doing many, many string searches using the STL string::find(). However, since I'm searching a very large string (up to a few megabytes), I'd like to limit the range in the string that I search. For instance, I'd like to find the string "abc" in strText, beginning the search at character 50 and ending the search at character 100. I don't care about the results if they appear after character 100. The string::find() allows you to specify the beginning position for the search, but not the ending position. How do I do this? [Edited by - BeanDog on March 25, 2006 1:25:19 PM]

Share this post


Link to post
Share on other sites
Close, but no cigar. That third parameter is actually the number of characters in the string you're searching for that you want to consider. For instance:

string strSearch = "abcdefg";
size_t pos = strSearch.find("cdXXX", 0, 2);
ASSERT(pos == 2);


That really confused me for a bit. Anyway, any other tips?

Share this post


Link to post
Share on other sites
Quote:
Original post by Zahlman
Why not just search in the desired .substr()? :)


Because the substring will often be small (~50 characters), but occasionally it will be large enough to incur a major memory allocation performance penalty.

Quote:
Original post by RDragon1
Try the generic std::find


std::find only finds individual elements. If I were looking for a single character, it would be the perfect solution. Unfortunately, I need to find a string.

Share this post


Link to post
Share on other sites

size_t FindInString(const std::string& str, const std::string& strSearch, size_t nMaxSize)
{
const char* pszSource = str.c_str();
for(size_t i=0; i<nMaxSize; ++i)
{
if(*pszSource == strSearch[0])
{
if(strcmp(pszSource+1,strSearch.c_str()+1) == 0)
return i;
}
++pszSource;
}

return std::string::npos;
}


That should do it.

Share this post


Link to post
Share on other sites
It would be better if that took 4 forward iterators - the beginning and end to search, and the beginning and end to find. But then you'd end up with std::search ;)

Not to mention it's prone to searching past the end of either string.

Share this post


Link to post
Share on other sites
Quote:
Original post by RDragon1
std::search
(Josuttis page 347)


Thanks! I've never had occasion to use this one before.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this