Looking for an equivalent to C++ std::getline in D

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 6 03:35:05 PDT 2017


On Saturday, 6 May 2017 at 10:15:03 UTC, k-five wrote:
> On Saturday, 6 May 2017 at 08:53:12 UTC, Jonathan M Davis wrote:
>> On Saturday, May 6, 2017 8:34:11 AM CEST k-five via 
>> Digitalmars-d-learn wrote:
>>> On Friday, 5 May 2017 at 17:07:25 UTC, Stanislav Blinov wrote:
>>> > On Friday, 5 May 2017 at 09:54:03 UTC, k-five wrote:
>
> ---------------------------------------------------------
>
> Although I am not sure but it may Range in D, has the same 
> concept that C++ has on iterator, like InputIterator or 
> OutputIterator, since I realized that the output of [ filter ] 
> does not have RandomAccessRange so I can not use input[ 0 ]. 
> But I can use input.front().
>
> Also thank you @Stanislav Blinov, I am familiar with lambda but 
> have never seen a lambda in shape of string :)
>
> ---------------------------------------------------------
>
> Solving the problem by using
> split and empty in std.string
> or splitter in std.algorithm or splitter in std.regex
>
> plus
> filter in std.algorithm,
> and accessing the elements by:
> input.front()
> input.popFront()
>
> ---------------------------------------------------------
>
> for input:
> import std.stdio : print = writeln;
> import std.algorithm: filter;
> import std.string: split, empty;
>
> void main() {
>
> 	immutable (char)[] str = "one//two//three";
> 	
> 	auto input = str.split( '/' ).filter!( element => 
> !element.empty
>  )();
> 	
> 	print( input.front );
> 	input.popFront();
> 	print( input.front );
> 	input.popFront();
> 	print( input.front );
>
> }
>
> the output is:
> one
> two
> three

str.split('/') is eager, that is, it will iterate the input and 
return the array of delimited elements. So in fact you're getting 
an array of all elements (even empty ones), and then filtering 
it, ignoring empty elements.
If you want to get the output as an array, it's better to use 
std.array as Jonathan mentioned:

import std.array : array;
auto inputArray = str.splitter('/').filter!(a => 
!a.empty)().array;

This will eagerly consume the results of filter and put them into 
an array.


More information about the Digitalmars-d-learn mailing list