在这里,我只需截断s
中的https
字母,任何人都可以帮助我如何从字符串下面截断这个字母吗?
https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg
答案 0 :(得分:5)
您真正想要的是从" https"更改方案到" http"在URL字符串中。可以使用URLComponents
类型安全地操作URL:
var urlString = "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg"
if var urlComponents = URLComponents(string: urlString), urlComponents.scheme == "https" {
urlComponents.scheme = "http"
urlString = urlComponents.string!
}
print(urlString)
// http://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg
如果您打算创建网址请求,那么您就不需要了
修改后的字符串,但仅包含已更改方案的URL(Request)
:
let urlString = "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg"
guard var urlComponents = URLComponents(string: urlString) else {
// ... invalid URL string, bail out ...
}
if urlComponents.scheme == "https" {
urlComponents.scheme = "http"
}
guard let url = urlComponents.url else {
// ... invalid URL, bail out ...
}
let request = URLRequest(url: url)
// ...
答案 1 :(得分:0)
尝试以下代码段:
let tmpStr = "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg"
let modifiedStr = tmpStr.replace("https", withString:"http")
extension String
{
func replace(target: String, withString: String) -> String
{
return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
}
}
答案 2 :(得分:-1)
使用方法replacingOccurrences(of:)可以轻松替换字符串中的文本。从swift2开始可以使用它。
let originalStr = "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg"
let finalStr = originalStr.replacingOccurrences(of: "https", with: "http")
print(finalStr)
<强>选项2 强>
let str = "https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg"
if str.utf16.count >= 5{
let a = str.index(str.startIndex, offsetBy: 5)
let result = String(str[..<a])
let replaced = str.replacingOccurrences(of: result, with: "http")
print(replaced)
}else{
//lenght in shorter
}
<强>选项3 强>
var str = "https://192.168.1.11/magento2/pub/https/ewl_bannerslider/slides/5.jpg"
str = str.stringByReplaceonFirstOccurrenceOfString(target: "https", withString: "http")
print(str)
extension String
{
func stringByReplaceonFirstOccurrenceOfString(
target: String, withString replaceString: String) -> String
{
if let range = self.range(of: target) {
return self.replacingCharacters(in: range, with: replaceString)
}
return self
}
}