我的字符串看起来像下面显示的数组。如何将此字符串转换为如下所示的数组?我已经尝试了this解决方案,但是我收到了来自Xcode的错误(由于信号分段错误导致命令失败11)并且我认为这对编译器来说太难了。
字符串:
var list = "<strong>UP</strong>, <strong>UP</strong>, <strong>DOWN</strong>, <strong>UP</strong>"
目标阵列:
var array = [<strong>UP</strong>, <strong>UP</strong>, <strong>DOWN</strong>, <strong>UP</strong>]
当我尝试let arr = list.characters.split {$0 == ","}
打印时:
[Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e40, _countAndFlags: 9223372036854775811, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e48, _countAndFlags: 9223372036854775812, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e52, _countAndFlags: 9223372036854775817, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e66, _countAndFlags: 9223372036854775816, _owner: nil)), Swift.String.CharacterView(_core: Swift._StringCore(_baseAddress: 0x0000000103152e78, _countAndFlags: 9223372036854775815, _owner: nil))]
使用空格(let arr = list.characters.split {$0 == ", "}
)会出现编译错误:
答案 0 :(得分:1)
有一个函数可以做到这一点,componentsSeparatedByString
var array = list.componentsSeparatedByString(", ")
答案 1 :(得分:0)
这会有效吗?
var list = "<strong>UP</strong>, <strong>UP</strong>, <strong>DOWN</strong>, <strong>UP</strong>"
do {
//Create a reggae and replace "," with any following spaces with just a comma
let regex = try NSRegularExpression(pattern: ", +", options: NSRegularExpressionOptions.CaseInsensitive)
list = regex.stringByReplacingMatchesInString(list, options: NSMatchingOptions.WithoutAnchoringBounds, range: NSMakeRange(0, list.characters.count), withTemplate: ",")
var array = list.characters.split { $0 == ","}.map(String.init)
} catch {
//Bad regex created
}
编辑:更新了示例,以便以原生的快速方式删除componentsSeparatedByString。您的示例的问题是结果数组不包含字符串,但似乎是一个名为CharacterView的内部类。将这些映射回字符串会产生所需的输出。
输出:
[
"<strong>UP</strong>",
"<strong>UP</strong>",
"<strong>DOWN</strong>",
"<strong>UP</strong>"
]