Swift中字符串的字符数组 [英] Character Array to string in Swift

查看:410
本文介绍了Swift中字符串的字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[字符]数组的输出当前为:

The output of the [Character] Array currently is:

["E", "x", "a", "m", "p", "l", "e"]

应该是:

Example

"可能在数组中,如下所示:""".该输出应为".

It could be that " is in the array, like this: """. That output should be ".

谢谢!

推荐答案

其他答案涉及数组是String元素之一的情况(在这种情况下很可能是这样:因为您没有向我们提供了数组的类型,我们可以使用Swift自己的类型推断规则来推测性推断类型为[String].

The other answer(s) cover the case where your array is one of String elements (which is most likely the case here: since you haven't supplied us the type of the array, we could use Swift own type inference rules to speculatively infer the type to be [String]).

如果您的数组元素实际上是Character类型,则可以使用 String Character序列初始化器直接:

In case the elements of your array are in fact of type Character, however, you could use the Character sequence initializer of String directly:

let charArr: [Character] = ["E", "x", "a", "m", "p", "l", "e"]
let str = String(charArr) // Example


W.r.t.您在下面的评论:如果由于某种原因您的示例数组是Any元素之一(通常不是明确使用的好主意,但有时是从某些外部源接收数据的情况),则首先需要执行在将转换后的元素浓缩为单个String实例之前,尝试将每个Any元素转换为String类型.转换后,您将使用String元素数组,在这种情况下,其他答案中显示的方法将是适当的浓缩方法:


W.r.t. your comment below: if your example array is, for some reason, one of Any elements (which is generally not a good idea to use explicitly, but sometimes the case when recieving data from some external source), you first need to perform an attempted conversion of each Any element to String type, prior to concenating the converted elements to a single String instance. After the conversion, you will be working with an array of String elements, in which case the methods shown in the other answers will be the appropriate method of concenation:

// e.g. using joined()
let arr: [Any] = ["E", "x", "a", "m", "p", "l", "e"]
let str = arr.flatMap { $0 as? String }.joined()
print(str) // example

您自然也可以(尝试)从Any转换为Character元素,但是即使在这种情况下,也必须通过String实例,这意味着对于[Any]情况,joined()上方的另一种方法是优先使用以下的方法:

You could naturally also (attempt to) convert from Any to Character elements, but even in this case you would have to go via String instances, which means that for the [Any] case, the joined() alternative above is to prefer over the one below:

let arr: [Any] = ["E", "x", "a", "m", "p", "l", "e"]
let str = String(arr.flatMap { ($0 as? String)?.characters.first })
print(str) // example

这篇关于Swift中字符串的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆