我尝试了很多选择,但无法解决。我在字符串变量中具有不同大小的URL。我只需要从其中删除http://。如何在Swift中做到这一点?
答案 0 :(得分:3)
您可能不希望删除n个字符,而是专门检查http(s)://
:
let string = "https://www.google.de"
let newString = str.replacingOccurrences(of: "https?://", with: "", options: .regularExpression, range: nil)
或者:
var str = "https://www.google.de"
if let httpRange = str.range(of: "https?://", options: .regularExpression, range: nil, locale: nil) {
str.removeSubrange(httpRange)
}
答案 1 :(得分:0)
为了最可靠地从网址中删除该方案,我将避免对方案进行硬编码:
import Foundation
let url = URL(string: "http://google.com")!
var string = url.absoluteString
if let scheme = url.scheme, string.hasPrefix(scheme) {
string.removeFirst(scheme.count + "://".count)
}
print(string)