The conventional way of finding a substring with size m in a string of n characters is implemented here, the performance is m*n and not really exciting. A better approach is using a data structure called “Suffix Array”
#include #include using namespace std; int find_substring(const char* mainString, const char* subString) { assert(mainString); assert(subString); int iFoundIndex = 0; const char* subPointer; bool bFound; for(; *mainString != 0; mainString++, iFoundIndex++) { for(bFound = true, subPointer = subString; *subPointer != 0; ++subPointer) { if(*(mainString + ((int)subPointer - (int)subString)) != *subPointer) { bFound = false; break; } } if(bFound) return iFoundIndex; } return -1; }
No comments:
Post a Comment