我在iPhone应用程序中有一个URL可供使用。但问题是它在URL中有一些空格。我想用'%20'替换空格。我知道有stringByReplacingOccurencesOfString
和stringByAddingPercentEscapesUsingEncoding
方法。我也用过它们。但他们不适合我。空格被一些不寻常的值取代。
我正在NSString
。
答案 0 :(得分:93)
从url替换空格的正确格式是:
目标C
NSString *urlString;//your url string.
urlString = [originalUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
或
urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iOS 9及更高版本
urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
斯威夫特:
var originalUrl = "https://google.com"
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
ios 9及更高版本
var urlString :String = originalUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
Swift 4
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
Swift 4.2
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
答案 1 :(得分:9)
Swift 2.0
array:4 [
0 => "10:00:00"
1 => "20:00:00"
2 => "00:00:00"
3 => "00:00:00"
]
<强>输出:强>
let originalUrl = "http://myurl.com/my photo.png"
let urlNew:String = urlReq.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())!
答案 2 :(得分:5)
替换 SWIFT 3 中出现的情况:
let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
答案 3 :(得分:4)
Swift 4
使用replacementOccurrences方法替换空格的另一种方法:
let yourString = "http://myurl.com/my photo.png"
let urlNew:String = yourString.replacingOccurrences(of: " ", with: "%20").trimmed
这将用'%20'
替换空格(“”)答案 4 :(得分:1)
迅速5.3,清除字符串的空格,
let str = " www.test.com "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(str) // "www.test.com"
答案 5 :(得分:0)
var urlString:String = originalUrl.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!
答案 6 :(得分:0)
Swift 4解决方案。您只需传递一个字符串,它就会用%20填充空格,并在字符串的开头添加“ http://”。真可爱!
URL(fileURLWithPath: String)
答案 7 :(得分:0)
雨燕5
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
答案 8 :(得分:0)
希望这会起作用
let url = "https:youtube.56432fgrtxcvfname=xyz&sname=tuv"
let urlNew:String = url.replacingOccurrences(of: " ", with: "%20")
Alamofire.request(urlNew, method: .get, headers: headers).responseJSON{
response in
print(response)
}
它将删除网址中的所有空格。
答案 9 :(得分:-1)
SWIFT 3.1
使用replacementOccurrences替换空格的简单方法:
URL = URL.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
答案 10 :(得分:-1)
Swift 4,iOS-9
let **urlSearchVal**:String = "top 10 movies"
let urlString =
"https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(urlSearchVal)&key=......&type=video"
//replace ...... above with your youtube key
// to ignoring white space in search
let UrlString :String = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!