我的代码片段是:
unwanted = " £€₹jetztabfromnow"
let favouritesPriceLabel = priceDropsCollectionView.cells.element(boundBy: UInt(index)).staticTexts[IPCUIAHighlightsPriceDropsCollectionViewCellPriceLabel].label
let favouritesPriceLabelTrimmed = favouritesPriceLabel.components(separatedBy: "jetzt").flatMap { String($0.trimmingCharacters(in: .whitespaces)) }.last
favouritesHighlightsDictionary[favouritesTitleLabel] = favouritesPriceLabelTrimmed
我的问题是,这不起作用:
let favouritesPriceLabelTrimmed = favouritesPriceLabel.components(separatedBy: unwanted).flatMap { String($0.trimmingCharacters(in: .whitespaces)) }.last
我有一个像“从 3,95 €”这样的价格 - 我想削减所有货币“£€₹”和像“from”或“ab”这样的词
你有适合我的解决方案吗?我可以在这里使用什么?
最佳答案
与其尝试替换或删除正确的字符或使用正则表达式,不如使用 Foundation 的内置语言标记支持。它将对字符串进行词法分析并返回各种类型的标记。在这种字符串上使用它,它应该可以可靠地找到字符串中的任何数字。
类似于:
var str = "from 3,95 €"
let range = Range(uncheckedBounds: (lower: str.startIndex, upper: str.endIndex))
var tokenRanges = [Range<String.Index>]()
let scheme = NSLinguisticTagSchemeLexicalClass
let option = NSLinguisticTagger.Options()
let tags = str.linguisticTags(in: range, scheme: scheme, options: option, orthography: nil, tokenRanges: &tokenRanges)
let tokens = tokenRanges.map { str.substring(with:$0) }
if let numberTagIndex = tags.index(where: { $0 == "Number" }) {
let number = tokens[numberTagIndex]
print("Found number: \(number)")
}
在此示例中,代码打印“3,95”。如果将 str
更改为“from £28.50”,它会打印“28.50”。
关于ios - 如何使用 Swift 3 修剪字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44568975/