在Swift 3中有
addingPercentEncoding
let originalString = "test/test"let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)print(escapedString!)
输出:
斯威夫特1测试%2Ftest
在iOS 7及更高版本中,
stringByAddingPercentEncodingWithAllowedCharacters
var originalString = "test/test"var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())println("escapedString: (escapedString)")
输出:
测试%2Ftest
以下是有用的(倒置)字符集:
URLFragmentAllowedCharacterSet "#%<>[]^`{|}URLHostAllowedCharacterSet "#%/<>?@^`{|}URLPasswordAllowedCharacterSet "#%/:<>?@[]^`{|}URLPathAllowedCharacterSet "#%;<>?[]^`{|}URLQueryAllowedCharacterSet "#%<>[]^`{|}URLUserAllowedCharacterSet "#%/:<>?@[]^`
如果要转义其他字符集,请创建一个字符集:
添加了“ =”字符的示例:
var originalString = "test/test=42"var customAllowedSet = NSCharacterSet(charactersInString:"="#%/<>?@\^`{|}").invertedSetvar escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)println("escapedString: (escapedString)")
输出:
测试%2Ftest%3D42
验证不在集合中的ASCII字符的示例:
func printCharactersInSet(set: NSCharacterSet) { var characters = "" let iSet = set.invertedSet for i: UInt32 in 32..<127 { let c = Character(UnipreScalar(i)) if iSet.longCharacterIsMember(i) { characters = characters + String(c) } } print("characters not in set: '(characters)'")}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)