替换URL中出现的空格
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了替换URL中出现的空格相关的知识,希望对你有一定的参考价值。
我在iPhone应用程序中有一个URL可供使用。但问题是它在URL中有一些空格。我想用'%20'替换空格。我知道有stringByReplacingOccurencesOfString
和stringByAddingPercentEscapesUsingEncoding
方法。我也用过它们。但他们不适合我。空格被一些不寻常的值取代。
我在NSString
的一个实例上应用这些方法。
答案
从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())!
斯威夫特4
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
Swift 4.2
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
另一答案
Swift 2.0
let originalUrl = "http://myurl.com/my photo.png"
let urlNew:String = urlReq.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())!
输出:
http://myurl.com/my%20photo.png
另一答案
要替换SWIFT 3中的出现:
let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
另一答案
斯威夫特4
用replacementOccurrences方法替换空格的另一种方法:
let yourString = "http://myurl.com/my photo.png"
let urlNew:String = yourString.replacingOccurrences(of: " ", with: "%20").trimmed
这将用'%20'替换空格(“”)
另一答案
一个Swift 4解决方案。您只需传递一个字符串,它用%20填充空格,并在字符串的开头添加“http://”。太可爱了!
URL(fileURLWithPath: String)
另一答案
斯威夫特5
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
另一答案
var urlString :String = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
另一答案
SWIFT 3.1
用replacementOccurrences替换空格的简单方法:
URL = URL.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
另一答案
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)!
以上是关于替换URL中出现的空格的主要内容,如果未能解决你的问题,请参考以下文章
结合两个代码片段?将用户输入的 Youtube url 转换为嵌入 url,然后将 iframe src 替换为转换后的 url