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

Started by
10 comments, last by RDragon1 18 years ago
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]
Advertisement
std::string does let you specify the end position.

One version of find lets you specify the length, the max number of characters to search through.
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?
Why not just search in the desired .substr()? :)
Try the generic std::find

Oh, you're looking to search for a string within...
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.
std::search

(Josuttis page 347)
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.
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.
Ah, I didn't know about std::search [smile] That'd be a better option probably.

This topic is closed to new replies.

Advertisement