Skip to content

Substring search

C++ nested loops

Flowchart (ISO 5807)

YesNoYesNoStartInput s, pn = |s|()m = |p|()i = 0, i + m ≤ n, i = i + 1j = 0j < m and s[i + j] = p[j]j = j + 1j = mReturn iEndReturn −1EndFigure 1 — indexOf

Source code

C++
int indexOf(string s, string p) {
    int n = s.length();
    int m = p.length();
    for (int i = 0; i + m <= n; i++) {
        int j = 0;
        while (j < m && s[i + j] == p[j]) {
            j++;
        }
        if (j == m) {
            return i;
        }
    }
    return -1;
}

The editor opens with this code — change it and the chart redraws.

Language
C++
Constructs
nested loops
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples