Swift:替换string中的字符 - 没有stringByReplacingOccurrencesOfString

时间:2014-07-02 11:10:31

标签: string replace swift

好的,所以说我有String喜欢

let myString = "my string: hello"

我想替换":"用","。我得到了这个:

let characters = map(Array(myString), {$0 == ":" ? "," : $0})

返回MapCollectionView<Array<Character>, Character>。有没有一种简单的方法可以将其转换回String

3 个答案:

答案 0 :(得分:4)

这个怎么样?通过&#34;将所有字符组合成一个字符串&#34;他们与+ 操作者:

let str = Array(characters).reduce("", combine: +)
println(str)
// Output: my string, hello

更新:另一种(可能更好的)解决方案:

var str = ""
str.extend(characters)

使用extend(),可以在没有中间Array的情况下完成字符串替换:

let myString = "my string: hello" as String
var myNewString = ""
myNewString.extend(map(myString.generate(), {$0 == ":" ? "," : $0} ))

答案 1 :(得分:2)

感谢Martin R的回答,我将代码缩减为:

let myString = "my string: hello" as String
let myNewString = Array(myString).reduce("") { $0 + (String($1) == ":" ? "," : String($1)) }

更新

从Xcode 6.2 beta开始,以下内容现在可以使用:

let myString = "my string: hello"
let result = String(map(Array(myString)) {$0 == ":" ? "," : $0})

// Output: my string, hello

答案 2 :(得分:0)

如何找到你想要的子串(也可以是单词),然后替换它们:

var aString = "Replace the letter e with *"

import Foundation
while let range: Range<String.Index> =  aString.rangeOfString("e") {
    aString.replaceRange(range, with: "*")
}

适用于Xcode 7.0.1