简体   繁体   English

如何在D中将字符串数组转换为字符串?

[英]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. 我需要从中创建string 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. 喜欢: "zxc", "asd", "qwe" (是的,每个元素都需要引用并用另一个逗号分隔,但它应该是字符串,而不是字符串数组。

How can I do it's in functional style? 我怎么能在功能风格上做到这一点?

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. std.algorithm.map采用一个lambda,它将范围内的元素转换为其他元素,并返回一个惰性范围,其中每个元素都是将元素从原始范围传递给lambda函数的结果。 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 string s which have quotes around them. 在这种情况下,lambda接受输入字符串并创建一个在其周围有引号的新字符串,因此将foo传递给它的结果是一系列string ,它们周围有引号。

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 string s it returns a string . std.array.join然后获取一个范围并急切地将每个元素与给定的分隔符连接起来,将每个元素分开并返回一个新数组,并且由于它给出了一系列string s,它返回一个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. 因此,通过给它调用map的结果和", "为分隔符,你得到的字符串由引用的原始字符串组成,并用逗号分隔。

std.algorithm.joiner would do the same thing as join , except that it results in a lazy range instead of an array. std.algorithm.joiner将与join做同样的事情,除了它导致惰性范围而不是数组。

Alternatively, use std.string.format Your format specifier should be something like this: auto joinedstring = format("%(\\“%s\\",%)", stringarray) 或者,使用std.string.format您的格式说明符应该是这样的:auto joinedstring = format(“%(\\”%s \\“,%)”,stringarray)

this is untested as I'm on mobile, but it's something similar to it! 这是未经测试的,因为我在移动设备上,但它与它类似!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM