As previously discussed, C++ took a surprisingly long time to get a "starts with" function for strings. It took even longer to get a function called "contains". In part, that's simply because string::find solves that problem.
Nancy sends us a… different approach to solving this problem.
bool substringInString(string str, string::iterator &it)
{
string tmp;
bool result = false;
int size = str.length();
int count = 0;
while (count < size)
{
tmp += *it;
it++;
count++;
if (tmp.find(str) != string::npos)
{
result = true;
it -= size;
break;
}
}
if ( !result)
{
it -= size;
}
return result;
}
This function iterates across a string, character by character. In this iteration, we copy one character at a time into tmp. Then we see if tmp contains our search str. If it does, we break out of the loop after rewinding the iterator. Outside of the loop, we check if we found the substring, and if we did, we rewind the iterator. Then we return true or false based on whether on not we found the substring.
So wait a second. str is our search string. it is where we're searching. And we copy from it up to our search string's length into a temporary string. We then do a find in that temporary string- hey! This is just a startsWith check written in the most insane way possible.
Why even bother with the while loop? While tmp is shorter than the search string, the answer is always "no, we haven't found it". And the developers knew that- that's why they always rewind size characters on the iterator. They're always searching exactly that many characters. Of course, since we always rewind the same amount, we can also just move the it -= size statement out of the loop and out of the if statement and do it once.
Nancy calls this "a little gem" in a "large codebase". Yeah, a real gem.
Your journey to .NET 9 is more than just one decision.Avoid migration migraines with the advice in this free guide. Download Free Guide Now!