ios - 如何使用 Swift 3 修剪字符串

标签 ios swift3 character-trimming

我的代码片段是:

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/

相关文章:

ios 7 展示了第一个带后退按钮的导航 Controller

ios - UICollectionView 的 SectionIndexTitles

swift - 具有关联类型类型转换的保护案例的单个表达式?

ios - 如何使用Swift3将NSMutableArray中的数据填充到结构中

swift - 从字符串中删除双引号 (")

php - 在迷你购物车中隐藏中间破折号(主题 functions.php)

ios - 在 iOS 应用程序安装上创建子文件夹

iOS setNeedsDisplay 在多个地区

swift - 嵌套调度组 Swift