Search code examples
d

convert string of int to array of int


Suppose I need to read a line from a file, containing an unknown number of space separated ints. How can I read a line and convert it into an array of ints?

What is one simple way of solving this problem in D?

My current non working attempt.

auto f = File("in");
foreach(line; f.byLine()){
  int[] arr;
  foreach(num; line.split())
    arr[] = cast(int)num;
}

Solution

  • Using splitter, map and array:

    import std.algorithm : map, splitter;
    import std.stdio : File;
    import std.conv : to;
    import std.array : array;
    
    void main(string[] args)
    {
        // range result
        auto result = File("in")
            .byLine
            .map!((line) => splitter(line).map!((a) => to!int(a)));
    
        // multidimensioanl array result
        int[][] resultArr = File("in")
            .byLine
            .map!((line) => splitter(line).map!((a) => to!int(a)).array).array;
    
    }