这可能是一个基本问题,但是我很难不包括 - 第二个
var title1 = "I will be part of string 1 - I am part of string 2"
let end = title1.range(of: "-", options: .backwards)?.lowerBound
let firstPartRange = title1.startIndex..<end!
var secondPart = title1.substring(with: firstPartRange) // Gives me "I will be part of string 1" which is correct
title1.substring(from: end!) // however this guy gives me "- I am part of string 2" & I only want to get "I am part of string 2" without the space and dash in front
我可以以某种方式改变范围或更改其下部?我知道我可以在此处通过函数用用户将组件用户分开,但是想学习如何抵消我的范围
您只需要在结束后获得索引或将其取代。请注意,您还应确保使用方法index(theIndex, offsetBy: n, limitedBy: endIndex)
let title1 = "I will be part of string 1 - I am part of string 2"
if let end = title1.range(of: "-", options: .backwards)?.lowerBound {
let firstPartRange = title1.startIndex..<end
let secondPart = title1.substring(with: firstPartRange) // "I will be part of string 1 "
title1.substring(from: title1.index(after: end)) // " I am part of string 2"
// or to offset it by two you should also make sure it doesn't pass the end index
title1.substring(from: title1.index(end, offsetBy: 2, limitedBy: title1.endIndex) ?? title1.endIndex) // "I am part of string 2"
}
您正在寻找index(_:offsetBy:)
。这是原始字符串的方法,例如:
var title1 = "I will be part of string 1 - I am part of string 2"
let end = title1.range(of: "-", options: .backwards)!.lowerBound
let ix = title1.index(end, offsetBy: 2)
title1.substring(from: ix) // "I am part of string 2"
您可以使用组件(分隔:字符串(方法将字符串的内容分开最后一个元素。
var title1 = "I will be part of string 1 - I am part of string 2"
print(title1.components(separatedBy: "-").last!.trimmingCharacters(in: .whitespacesAndNewlines))
它将为您提供所需的结果
"我是字符串2"
的一部分
希望它有帮助!
您可以使用组件函数,并在分隔器中包含空格:
title1.components(separatedBy:" - ")
@matt建议,您正在寻找 index(_:offsetBy:)
仅使用SWIFT标准库(无基础(
有点不同的方法let str = "I will be part of string 1 - I am part of string 2"
let parts = str.characters.split(separator: "-").map(String.init)
如果您想修剪所有额外的空间
let partsTrimmed = parts.map {
$0.characters.split(separator: " ").map(String.init).joined(separator: " ")
}