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?
2 Replies - 125 Views - Last Post: 09 January 2013 - 12:46 PM
#1
Seeing if a std::string contains a particular substring efficiently
Posted 09 January 2013 - 12:31 PM
Replies To: Seeing if a std::string contains a particular substring efficiently
#2
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:
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.
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
#3
Re: Seeing if a std::string contains a particular substring efficiently
Posted 09 January 2013 - 12:46 PM
Alright, thanks!
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote



|