Swift:替换字符串中的字符 - 没有 stringByReplacingOccurrencesOfString [英] Swift: replace character in string - without stringByReplacingOccurrencesOfString
本文介绍了Swift:替换字符串中的字符 - 没有 stringByReplacingOccurrencesOfString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,假设我有一个 String
像
OK, so say I have a String
like
let myString = "my string: hello"
我想用,"替换:".我做到了:
and I want to replace ":" with ",". I got as far as this:
let characters = map(Array(myString), {$0 == ":" ? "," : $0})
返回一个 MapCollectionView
.有没有一种简单的方法可以将其转换回 String
?
Which returns a MapCollectionView<Array<Character>, Character>
. Is there a simple way to convert this back into a String
?
推荐答案
这个呢?通过使用 +
减少"它们将所有字符组合成一个字符串操作员:
What about this? Combine all characters to a string by "reducing" them with the +
operator:
let str = Array(characters).reduce("", combine: +)
println(str)
// Output: my string, hello
更新:另一种(也许更好)的解决方案:
Update: An alternative (perhaps nicer) solution:
var str = ""
str.extend(characters)
使用extend()
,可以在没有中间Array
的情况下完成字符串替换:
Using extend()
, the string replacement could be done without an intermediate Array
:
let myString = "my string: hello" as String
var myNewString = ""
myNewString.extend(map(myString.generate(), {$0 == ":" ? "," : $0} ))
这篇关于Swift:替换字符串中的字符 - 没有 stringByReplacingOccurrencesOfString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文