How to use retro over findSplitBefore result?

Jesse Phillips Jesse.K.Phillips+D at gmail.com
Wed Dec 4 10:01:51 PST 2013


On Wednesday, 4 December 2013 at 17:43:22 UTC, MrSmith wrote:
> I am trying to compile following code
>
> import std.algorithm : findSplitBefore;
> import std.range : retro;
> import std.array : array;
>
> // returns file path where name has suffix and prefix
> string withSuffixPrefix(string filePath, string prefix, string 
> suffix)
> {
>     auto splitted = filePath.retro.findSplitBefore("/");
>
>     return cast(string)splitted[1].retro.array
> 		~ prefix
> 		~ cast(string)splitted[0].retro.array //Fails!
> 		~ suffix;
> }

The casting you've placed in there scares me. The returned range 
is going to be of dchar, assuming you're interested in UTF 
support, you'll want a conversion not a cast, I recommend 
std.conv.to!string. But even this is too much so I've commented 
that out and replaced it with a somewhat lazy approach:

import std.algorithm : findSplitBefore;
import std.range : retro, chain;
import std.array : array;
import std.conv : to;

// returns file path where name has suffix and prefix
string withSuffixPrefix(string filePath, string prefix, string
suffix)
{
     auto splitted = filePath.retro.findSplitBefore("/");

     //return splitted[1].array.retro.to!string
	//	~ prefix
	//	~ splitted[0].array.retro.to!string
	//	~ suffix;
     return chain(splitted[1].array.retro,
		prefix,
		splitted[0].array.retro,
		suffix).array;
}

void main() {
	assert(withSuffixPrefix("/some/random/path/to/file", "pref-",
		  ".fl") == "/some/random/path/to/pref-file.fl");
}


More information about the Digitalmars-d-learn mailing list