2

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?

Suliman
  • 1,469
  • 3
  • 13
  • 19

2 Answers2

7
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.

Jonathan M Davis
  • 37,181
  • 17
  • 72
  • 102
0

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!

Colin Grogan
  • 2,462
  • 3
  • 12
  • 12
  • You don't need to escape the inner quotes if you use backtick quotes or raw strings. `format(r"%("%s", %)", stringarray)` – Meta Mar 04 '15 at 21:59