reading file byLine

wobbles via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 2 15:19:06 PDT 2015


On Wednesday, 2 September 2015 at 21:53:20 UTC, Namal wrote:
> Thx guys, this helped alot. The next thing I want to do is read 
> the file line by line and split the stream into words. I found 
> this example of code that seems to do sort of something like 
> it. How can I modyfy it so I can store the words in an array of 
> strings? Is a => a.length the iterator range?
>
>
> import std.algorithm, std.stdio, std.string;
> // Count words in a file using ranges.
> void main()
> {
>     auto file = File("file.txt"); // Open for reading
>     const wordCount = file.byLine()            // Read lines
>                           .map!split           // Split into 
> words
>                           .map!(a => a.length) // Count words 
> per line
>                           .sum();              // Total word 
> count
>     writeln(wordCount);
> }


I would do what you want like this

auto file = File("file.txt");
auto words = file.byLine()           // you've all lines in  range
                  .map!(a => a.split); // read each line, 
splitting it into words
                                      // now you've a range, where 
each element is an array of words

The map!(a => a.split) line simply maps each element to the 
return value of a.split - this is the predicate.

The a => a.split syntax is a lambda expression that tells map 
what to do on each element.


More information about the Digitalmars-d-learn mailing list