题目:将字符串中的空格替换成“%20”,当字符串为I am FlyElephat,替换之后的字符串为I%20am%20FlyElephant.
最简单的方式就是遍历字符串之后,进行字符串拼接:
<pre><code>` func replaceSpaces(str:String) -> String {
var result:String = ""
for i in 0..<str.characters.count {
if str[i] == " " {
result.append("%20")
} else {
result.append(str[i] as Character)
}
}
return result
}`</code></pre>
还可以通过字符串空格的数量,对字符串进行两次扫描,从后向前替换空格.
<pre><code>` func replaceSpaces1(str:String) -> String {
var spaceCount:Int = 0
let count:Int = str.characters.count
for i in 0..<count {
if (str[i] as Character) == " " {
spaceCount += 1
}
}
let charCount:Int = count + spaceCount * 2
var chars:[Character] = [Character].init(repeating: " ", count: charCount)
var index:Int = charCount - 1
for i in stride(from: count - 1, to: -1, by: -1) {
if (str[i] as Character) == " " {
chars[index] = "0"
chars[index - 1] = "2"
chars[index-2] = "%"
index -= 3
} else {
chars[index] = str[i] as Character
index -= 1
}
}
return String(chars)
}`</code></pre>
测试代码:
<pre><code>`var replaceStr:String = "I am FlyElephant"
var replaceResult:String = myString.replaceSpaces(str: replaceStr)
print("字符串空格替换:(replaceResult)")
var result2:String = myString.replaceSpaces1(str: replaceStr)
print("字符串空格替换:(result2)")`</code></pre>