www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Stuck with std.algorithm.splitter

reply =?UTF-8?B?QWxla3NhbmRhciBSdcW+acSNacSH?= <ruzicic.aleksandar gmail.com> writes:
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)...
Apr 03 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
Aleksandar R.:

 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
 -------------------------------------------------
import std.stdio, std.array; void main() { string input = "foo|bar"; //auto parts = split(input, '|'); // nope string[] parts = split(input, "|"); if (parts.length > 1) writefln("%s, %s", parts[0], parts[1]); else writefln("%s", parts[0]); } Bye, bearophile
Apr 03 2011
parent =?UTF-8?B?QWxla3NhbmRhciBSdcW+acSNacSH?= <ruzicic.aleksandar gmail.com> writes:
I haven't even looked into std.array... sorry..

So I won't need custom function after all. Thanks!
Apr 03 2011