[英]how to truncate a character in string?
在这里,我只需要截断https
的s
字母,有人可以帮助我如何从字符串下面截断它吗?
https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg
您真正想要的是将URL字符串中的方案从“ https”更改为“ http”。 可以使用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请求,那么您不需要修改后的字符串,而只需要使用已更改方案的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)
// ...
请尝试以下代码片段:
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)
}
}
借助方法replaceOccurrences (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
}
2选项
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.