www.digitalmars.com [Home] [Search] [D]

Example: wc

This program is the D version of the classic wc (wordcount) C program. It serves to demonstrate how to read files, do array slicing, and simple symbol table management with associative arrays.
import stdio;
import file;

int main (char[][] args)
{
    int w_total;
    int l_total;
    int c_total;
    int[char[]] dictionary;

    printf("   lines   words   bytes file\n");
    for (int i = 1; i < args.length; ++i)
    {
	char[] input;
	int w_cnt, l_cnt, c_cnt;
	int inword;
	int wstart;

	input = File.read(args[i]);

	for (int j = 0; j < input.length; j++)
	{   char c;

	    c = input[j];
	    if (c == "\n")
		++l_cnt;
	    if (c >= "0" && c <= "9")
	    {
	    }
	    else if (c >= "a" && c <= "z" ||
		c >= "A" && c <= "Z")
	    {
		if (!inword)
		{
		    wstart = j;
		    inword = 1;
		    ++w_cnt;
		}
	    }
	    else if (inword)
	    {	char[] word = input[wstart .. j];

		dictionary[word]++;
		inword = 0;
	    }
	    ++c_cnt;
	}
	if (inword)
	{   char[] word = input[wstart .. input.length];
	    dictionary[word]++;
	}
	printf("%8lu%8lu%8lu %s\n", l_cnt, w_cnt, c_cnt, (char *)args[i]);
	l_total += l_cnt;
	w_total += w_cnt;
	c_total += c_cnt;
    }

    if (args.length > 2)
    {
	printf("--------------------------------------\n%8lu%8lu%8lu total",
	    l_total, w_total, c_total);
    }

    printf("--------------------------------------\n");
    char[][] keys = dictionary.keys;
    for (int i = 0; i < keys.length; i++)
    {	char[] word;

	word = keys[i];
	printf("%3d %.*s\n", dictionary[word], word);
    }
    return 0;
}

Copyright (c) 1999-2001 by Digital Mars, All Rights Reserved