C++ Index of Strings
One of the most commonly used String functions is the IndexOf function. Let's see what it does:
std::string s = "Text";
// returns 1 because 'ext' is on the position 1 in s
int index = IndexOf(s, "ext");
// returns -1 because 'ABC' is not in s
int index = IndexOf(s, "ABC");
// returns 2 because 'xt' is on the position 2 in s
int index = IndexOf(s, "xt");
IndexOf is a really useful function, so let's implement it!
This function will be used very often, so our goal is to implement it as efficient as possible. There are several algorithms that do this in a different way with a different speed. To keep it simple, we will just use the one that our C++ Standard Library offers - it's usually optimized very good.
Here we go:
int indexof(std::string& text, std::string& pattern)
// where appears the pattern in the text?
std::string::size_type loc = text.find(pattern, 0);
if(loc != std::string::npos)
Keep in mind that this function will always return the index of the pattern in the text, and if it's not found then it will return -1.