Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

Word Count

This program is the D version of the classic wc (wordcount) C program. It serves to demonstrate how to read files, slice arrays, and simple symbol table management with associative arrays.

import std.stdio;
import std.algorithm;

void main(string[] args)
    ulong wordCount;
    ulong lineCount;
    ulong charCount;

    int[string] dictionary;
    writeln("   lines   words   bytes file");

    foreach (arg; args[1 .. $])
        ulong lWordCount;
        ulong lCharCount;
        ulong lLineCount;

        auto file = File(arg);
        foreach (line; file.byLine(KeepTerminator.yes))
            lCharCount += line.length;
            foreach (word; splitter(line))
                lWordCount += 1;
                if (auto count = word in dictionary)
                    *count += 1;
                    dictionary[word.idup] = 1;

            lLineCount += 1;

        writefln("%8s%8s%8s %s\n", lLineCount, lWordCount, lCharCount, arg);

        wordCount += lWordCount;
        lineCount += lLineCount;
        charCount += lCharCount;

    const char[37] hr = '-';

    if (args.length > 2)
        writefln("%8s%8s%8s total", lineCount, wordCount, charCount);


    foreach (word; sort(dictionary.keys))
            writefln("%3s %s", dictionary[word], word);