liveBook · Manning

Substring

As explained in Learn C++ by Example

A substring is a contiguous sequence of characters taken from a string.

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

How Learn C++ by Example covers it

How deep it goes
Explains substring extraction through working C++ code, prefix comparison, repeated offsets, and a no-match result.
Examples
Demonstrates word.substr(1) producing "har", matching "harsh", and shortening "struct" through successive offsets.
What it assumes
Assumes basic C++ strings, indexing, loops, and maps while introducing substring-based searching in context.
What you can do after
Apply it via C++ string APIs to extract prefixes, compare stems, and assemble overlapping words.
How it connects
Connects substrings with strings, maps, dictionary lookup, prefixes, offsets, and optional failure results.

Also explained in

Compare how 5 books explain substring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.