[英]how to truncate a character in string?
在这里,我只需要截断https
的s
字母,有人可以帮助我如何从字符串下面截断它吗?
https://192.168.1.11/magento2/pub/media/ewl_bannerslider/slides/5.jpg
What you actually want is to change the scheme from "https" to "http" in an URL string. 您真正想要的是将URL字符串中的方案从“ https”更改为“ http”。 URLs can be safely manipulated using the URLComponents
type: 可以使用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
If your intention is to create an URL request then you don't need the modified string, but only the URL(Request)
with the changed scheme: 如果您打算创建一个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)
// ...
Try below code snippet: 请尝试以下代码片段:
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)
}
}
It's easy to replace text inside a string with the help of the method replacingOccurrences(of:) it is available from swift2 onwards. 借助方法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)
option2 选项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
}
option3 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.