Suliman
Suliman

Reputation: 1509

How to convert array of strings to string in D?

I have got array of strings like:

string [] foo = ["zxc", "asd", "qwe"];

I need to create string from them. Like: "zxc", "asd", "qwe" (yes every elements need be quoted and separate with comma from another, but it should be string, but not array of strings.

How can I do it's in functional style?

Upvotes: 2

Views: 115

Answers (2)

Colin Grogan
Colin Grogan

Reputation: 2842

Alternatively, use std.string.format Your format specifier should be something like this: auto joinedstring = format("%(\“%s\",%)", stringarray)

this is untested as I'm on mobile, but it's something similar to it!

Upvotes: 0

Jonathan M Davis
Jonathan M Davis

Reputation: 38297

import std.algorithm, std.array, std.string;
string[] foo = ["zxc", "asd", "qwe"];
string str = foo.map!(a => format(`"%s"`, a)).join(", ");
assert(str == `"zxc", "asd", "qwe"`);

std.algorithm.map takes a lambda which converts an element in the range into something else, and it returns a lazy range where each element is the result of passing an element from the original range to the lambda function. In this case, the lambda takes the input string and creates a new string which has quotes around it, so the result of passing foo to it is a range of strings which have quotes around them.

std.array.join then takes a range and eagerly concatenates each of its elements with the given separator separating each one and returns a new array, and since it's given a range of strings it returns a string. So, by giving it the result of the call to map and ", " for the separator, you get your string made up of the original strings quoted and separated by commas.

std.algorithm.joiner would do the same thing as join, except that it results in a lazy range instead of an array.

Upvotes: 7

Related Questions