Stuck with std.algorithm.splitter

Jonathan M Davis jmdavisProg at gmx.com
Sun Apr 3 16:52:08 PDT 2011


On 2011-04-03 16:34, Aleksandar Ružičić wrote:
> I want to split a string into an array of strings. As much as it seems
> trivial I just can't make it work.
> 
> This is code I use for splitting:
> 
> -------------------------------------------------
> auto input = "foo|bar";             // sample input string
> auto parts = splitter(input, '|');  // split by pipe character
> -------------------------------------------------
> 
> now, I would think that parts is an array. But it doesn't have .length
> property! Thus, I have to use walkLength:
> 
> -------------------------------------------------
> if (walkLength(parts, 2) > 1) {
> 	writefln("%s, %s", parts[0], parts[1]);
> } else {
> 	writefln("%s", parts[0]);
> }
> -------------------------------------------------
> 
> and problem with missing .length is gone, but now I cannot access
> those elements using array indexing:
> 
> test.d(14): Error: no [] operator overload for type Splitter!(string,char)
> test.d(14): Error: no [] operator overload for type Splitter!(string,char)
> test.d(16): Error: no [] operator overload for type Splitter!(string,char)
> 
> So, parts isn't an array but Splitter!(string,char), aha!
> But as much as I've tried I cannot find a way to access elements of
> Splitter by index. I've gone trough std.range and std.algorithm but
> found nothing useful...
> 
> I would really like to use library function for this instead to write
> my own (foreach and array slicing comes to my mind)...

Splitter is not a random-access range. What type of range that it actually is 
depends on what it's splitting, but it doesn't appear to ever be a random-
access range (which makes sense when you think about how it works). It's 
lazily splitting the range, so it _can't_ be random-access. If you want an 
actual array, then simply use array on it.

auto parts = array(splitter(input, '|'));

Then you'll have an array of strings to use. That _does_ copy the data though, 
so it's not something that you'd generally want to do if all you're doing is 
iterating through the result of splitter.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list