2 Replies - 205 Views - Last Post: 09 January 2013 - 12:46 PM Rate Topic: -----

#1 arcsss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 03-January 13

Seeing if a std::string contains a particular substring efficiently

Posted 09 January 2013 - 12:31 PM

As the title says, I'd like to see if a substring of a string is at a particular position within the string. Let's say I have the string "IDENTIFIER 10239", and I want to see if "IDENTIFIER" is the first 10 letters within the string. I could do something like !str.substr(0,10).compare("IDENTIFIER"), and this works fine. Could there be a more efficient way of doing it, though? I could do something like str.size() > 9 && str[0] == 'I' && str[1] == 'D", etc, but that seems like a very long way of going about it (could be simplified with a loop, but still...). I could also use str.find("IDENTIFIER"), but there's no option for me to limit the upper bound of the search area, just the lower bound. Does a better way exist?

Is This A Good Question/Topic? 0
  • +

Replies To: Seeing if a std::string contains a particular substring efficiently

#2 vividexstance  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 660
  • View blog
  • Posts: 2,270
  • Joined: 31-December 10

Re: Seeing if a std::string contains a particular substring efficiently

Posted 09 January 2013 - 12:38 PM

The way you're doing now should be efficient enough. You do the check in 1 line of code, where you would probably need more than that to do it another way.

Remember this quote:

Quote

Premature optimization is the root of all evil.

Just try to focus on getting the code to work, and in the end, if you really need to make your code more efficient, then you should run a profiler and see where the bottleneck(s) are, and work on making them more efficient.

This post has been edited by vividexstance: 09 January 2013 - 12:40 PM

Was This Post Helpful? 1
  • +
  • -

#3 arcsss  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 03-January 13

Re: Seeing if a std::string contains a particular substring efficiently

Posted 09 January 2013 - 12:46 PM

Alright, thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1