2014-07-02 185 views
18

嗨,大家好我有变量,其中的符号或字符的内容我不知道你怎么说这个“\”在英语中...如何用我的变量中的空白空间替换所有\Swift - 替换字符串中的字符

var content = theContent["content"] as String 
self.contentLabel.text = content.stringByReplacingOccurrencesOfString(<#target: String#>, withString: <#String#>, options: <#NSStringCompareOptions#>, range: <#Range<String.Index>?#>) 

如何来填补这个空间或我的sintax是错误的,当我使用content.string ......然后在#target我使用相同字符串?任何人如此快速地学习Swift? :d

回答

28

使用以下

self.contentLabel.text = content.stringByReplacingOccurrencesOfString("\\", withString: " ", options: NSStringCompareOptions.LiteralSearch, range: nil) 
14

如果你想在斯威夫特写这个,试试:

self.contentLabel.text = Array(myString).reduce("") { $1 == "\\" ? $0 : "\($0)\($1)" } 

这是写作的手短方式:

Array(myString).reduce("", combine: { (inputString, character) -> String in 
    if character == "\\" { 
     return inputString 
    } else { 
     return "\(inputString)\(character)" 
    } 
}) 

这将myString转换为ArrayCharacter s,然后使用reduce函数将它们追加在一起成为String,但用空字符串代替反斜杠

+0

您是什么意思纯粹的swift?这看起来很激烈。你能解释一下在这个例子中发生了什么? – Aggressor

+3

By * pure * Swift,我的意思是它没有使用任何基础类(例如NSString) - 为了清晰起见更新了我的答案 –