Word Count - D Programming Language
Description: D Programming Language
Keywords: D programming language

Menu

- Learn
- Documentation
  - Language Reference
  - Library Reference
  - Command-line Reference
  - Feature Overview
  - Articles
- Downloads
- Packages
- Community
  - Blog
  - Orgs using D
  - Twitter
  - Forums
  - IRC
  - Community Discord
  - Wiki
  - GitHub
  - Issues
  - Get involved
  - Contributors
  - Foundation
  - Security Team
  - Donate
  - Sponsors
- Resources
  - Tour
  - Books
  - Tutorials
  - Tools
  - Editors
  - IDEs
  - run.dlang.io
  - Visual D
  - Acknowledgments
  - D Style
  - Glossary
  - Sitemap

Search
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;
                    else
                        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)
        {
            writeln(hr);
            writefln("%8s%8s%8s total", lineCount, wordCount, charCount);
        }

        writeln(hr);

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

Copyright © 1999-2023 by the D Language Foundation | Page generated by Ddoc on Fri Jun 2 09:00:03 2023