這是不夠清楚自己想要做什麼,但我想你想要做這樣的事情:
extension String {
var modifiedString: String {
var outString = ""
for thisChar in self.characters {
if thisChar == " " {
let charCode = String(thisChar).unicodeScalars.first!.value
outString += "%" + String(format: "%02X", charCode)
//### Or if you prefer... (Do not miss, you need 3 '%'s in the format string.)
//outString = outString.appendingFormat("%%%02X", charCode)
} else {
outString.append(thisChar)
}
}
return outString
}
}
print("what you really want to do?".modifiedString)
//->what%20you%20really%20want%20to%20do?
與for thisChar in self.characters
循環的thisChar
類型變得Character
,它不是易於從Swift中的Character
獲得字符代碼。
可能有一些更好的方法,但let charCode = String(thisChar).unicodeScalars.first!.value
按預期工作,當thisChar
只包含一個UnicodeScalar
。
你應該更好地瞭解雨燕的方法命名爲addingPercentEncoding
:
let result = "what you really want to do?".addingPercentEncoding(withAllowedCharacters: CharacterSet.whitespaces.inverted)!
print(result)
//->what%20you%20really%20want%20to%20do?
你真的想做些什麼?即使你修正了這個錯誤,你的代碼也會充滿奇怪的東西。 - 缺少回報。 - appendingFormat不修改'outString',所以'for循環結束時它的值是空的。 - 格式'「%% 02X」'不會消耗參數並生成'「%02X」'。 - 白色字幕以外的所有字符均被忽略。 – OOPer
您是否嘗試將ASCII值轉換爲十六進制數字?也許你應該使用'.utf8'而不是'.characters'? – Sulthan
另外,你只編碼空格字符,因爲'if thisChar ==「」'? – Sulthan