我想删除所有出现的char ==。在除最后一个之外的字符串中。
E.G:
var amazon = require('amazon-product-api');
var client = amazon.createClient({
awsId: "aws ID",
awsSecret: "aws Secret",
awsTag: "aws Tag"
});
应该成为:
1.2.3.4
答案 0 :(得分:4)
示例:
var str = "1.2.3.4"
if let idx = str.range(of: ".", options: .backwards) {
str = str.replacingOccurrences(of: ".", with: "", range: str.startIndex..<idx.lowerBound)
}
print(str) // 123.4
答案 1 :(得分:3)
以下是示例代码。按角色分割,将该角色添加到最后一个元素的开头,然后再将它们连接起来
let str = "1.2.3.4"
var array = str.components(separatedBy: ".")
if array.count >= 1 {
array[array.count - 1] = "." + array[array.count - 1]
}
print(array.joined(separator: ""))
答案 2 :(得分:1)
您可以将此简易重用作为String的扩展名。
public extension String {
func stringByReplacingAllButLastOccurrenceOfString(target: String, withString replaceString: String) -> String {
if let idx = self.rangeOfString(target, options: .BackwardsSearch) {
return self.stringByReplacingOccurrencesOfString(target, withString: replaceString, range: self.startIndex..<idx.first!)
}
return self
}
}
通过一些场景,你得到:
strResult = "1.2.3.4.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "1234.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "1.23.4.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "1234.5".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "1234.5"
strResult = "12345".stringByReplacingAllButLastOccurrenceOfString(".", withString: "")
// result "12345"