Listing 1: BuildingFSM.cpp — Sample code to enter a single substring into the FSM

// Enter each substring (pSubStr), in turn, stopping when we 
// reach its end (lSubstringLength), or if we reach a previous
// full-string match (denoted by lCurrentState==-1) 
// Only create new states when they are needed, and then increment
// the lMaxUsedState counter

long lCurrentState = 0;
for (int i=0; (i<lSubstringLength)  &&  (lCurrentState!=-1); i++)
{
  // special case - last character of substring
  if (i == (lSubstringLength-1) )
    lCurrentState = FSM[lCurrentState][pSubStr[i]] = -1;
  else
  {    
    // add to FSM, if current entry for this character value
    //  and state is still zero 
    if (FSM[lCurrentState][pSubStr[i]] == 0)
      lCurrentState = FSM[lCurrentState][pSubStr[i]] = 
        ++lMaxUsedState;
    // or simply record an existing value as the current state 
    // (following state path of a previous substring)
    else
      lCurrentState = FSM[lCurrentState][pSubStr[i]];
  }
}
— End of Listing —