A substring is a contiguous part of a string. In the answer-smash game, substrings help find dictionary words that overlap a keyword. Starting at index 1 avoids swallowing the whole word, then the search advances until it finds a matching stem or exhausts the possible overlaps. section 7.1.3
Finding an overlapping word
For "char", word.substr(1) produces "har". The dictionary key "harsh" begins with that stem, so the game can combine the retained prefix "c" with "harsh" to produce "charsh". If no stem matches, the function returns an empty word and offset -1. section 7.1.3
Listing 7.5 Finding an overlapping word
#include <map>
#include <string>
#include <utility>
#include "Smash.h"
std::pair<std::string, int> find_overlapping_word(std::string word,
const std::map<std::string, std::string>& dictionary)
{
size_t offset = 1; #1
while (offset < word.size())
{
auto stem = word.substr(offset);
for (const auto & [k, v] : dictionary) #2
{ #2
auto key_stem = k.substr(0, stem.size()); #2
if (key_stem == stem) #3
{ #3
return { k, offset }; #3
}
}
++offset; #4
} #4
return { "", -1 }; #4
}
Inspect the complete C++ search function: it creates progressively shorter substrings, compares each with a dictionary-key prefix, and reports the first match. section 7.1.3




