@@ -488,88 +488,49 @@ $(H2 $(LNAME2 examples, Examples))
488
488
489
489
$(H3 $(LNAME2 aa_example, Associative Array Example: word count))
490
490
491
- $(P Let's consider the file is ASCII encoded with LF EOL.
492
- In general case we should use $(I dchar c) for iteration
493
- over code points and functions from $(LINK2 $(ROOT_DIR)phobos/std_uni.html,std.uni).
494
- )
495
-
496
- $(SPEC_RUNNABLE_EXAMPLE_COMPILE
491
+ $(RUNNABLE_EXAMPLE
492
+ $(RUNNABLE_EXAMPLE_STDIN
493
+ too many cooks
494
+ too many ingredients
495
+ )
497
496
---------
498
- import std.algorithm : sort;
499
- import std.file; // D file I/O
497
+ import std.algorithm;
500
498
import std.stdio;
501
- import std.ascii;
502
499
503
- void main(string[] args )
500
+ void main()
504
501
{
505
- ulong totalWords, totalLines, totalChars;
506
502
ulong[string] dictionary;
503
+ ulong wordCount, lineCount, charCount;
507
504
508
- writeln(" lines words bytes file");
509
- foreach (arg; args[1 .. $]) // for each argument except the first one
505
+ foreach (line; stdin.byLine(KeepTerminator.yes))
510
506
{
511
- ulong wordCount, lineCount, charCount;
512
-
513
- foreach (line; File(arg).byLine())
507
+ charCount += line.length;
508
+ foreach (word; splitter(line))
514
509
{
515
- bool inWord;
516
- size_t wordStart;
517
-
518
- void tryFinishWord(size_t wordEnd)
519
- {
520
- if (inWord)
521
- {
522
- auto word = line[wordStart .. wordEnd];
523
- ++dictionary[word.idup]; // increment count for word
524
- inWord = false;
525
- }
526
- }
527
-
528
- foreach (i, char c; line)
529
- {
530
- if (std.ascii.isDigit(c))
531
- {
532
- // c is a digit (0..9)
533
- }
534
- else if (std.ascii.isAlpha(c))
535
- {
536
- // c is an ASCII letter (A..Z, a..z)
537
- if (!inWord)
538
- {
539
- wordStart = i;
540
- inWord = true;
541
- ++wordCount;
542
- }
543
- }
544
- else
545
- tryFinishWord(i);
546
- ++charCount;
547
- }
548
- tryFinishWord(line.length);
549
- ++lineCount;
510
+ wordCount += 1;
511
+ if (auto count = word in dictionary)
512
+ *count += 1;
513
+ else
514
+ dictionary[word.idup] = 1;
550
515
}
551
516
552
- writefln("%8s%8s%8s %s", lineCount, wordCount, charCount, arg);
553
- totalWords += wordCount;
554
- totalLines += lineCount;
555
- totalChars += charCount;
517
+ lineCount += 1;
556
518
}
557
519
520
+ writeln(" lines words bytes");
521
+ writefln("%8s%8s%8s", lineCount, wordCount, charCount);
522
+
558
523
const char[37] hr = '-';
559
- if (args.length > 2)
560
- {
561
- writeln(hr);
562
- writefln("%8s%8s%8s total", totalLines, totalWords, totalChars);
563
- }
564
524
565
525
writeln(hr);
566
- foreach (word; dictionary.keys.sort )
526
+ foreach (word; sort( dictionary.keys) )
567
527
{
568
528
writefln("%3s %s", dictionary[word], word);
569
529
}
570
530
}
571
531
---------
572
532
)
533
+ $(P See $(DDLINK wc, wc, wc) for the full version.)
573
534
574
535
$(H3 $(LNAME2 aa_example_iteration, Associative Array Example: counting pairs))
575
536
0 commit comments