Skip to content

Word count

TypeScript loop over characters

Flowchart (ISO 5807)

YesYesNoNoStartInput scount = 0inWord = falsei = 0, |s| − 1, 1s[i] ≠ « »not inWordcount = count + 1inWord = trueinWord = falseReturn countEndFigure 1 — wordCount

Source code

TypeScript
function wordCount(s: string): number {
    let count = 0;
    let inWord = false;
    for (let i = 0; i < s.length; i++) {
        if (s[i] !== " ") {
            if (!inWord) {
                count++;
                inWord = true;
            }
        } else {
            inWord = false;
        }
    }
    return count;
}

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

Language
TypeScript
Constructs
loop over characters
Topic
Loops
Formats
Word, Visio, draw.io, PDF, SVG

Related examples