【问题标题】:How to select a word in a string only if it is longer then two characters in Swift只有当它长于 Swift 中的两个字符时,如何在字符串中选择一个单词
【发布时间】:2021-02-25 10:45:27
【问题描述】:

给定一个像“区域城市”这样的字符串,我可以通过数组索引获取我需要的单个单词,但是如何跳过诸如“的”这样的短单词并获取区域?

let fullName = model.institution?.nome ?? "N/A"
let firstWord = fullName.components(separatedBy: " ").first ?? "N/A"
var seconWord = ""       
if fullName.components(separatedBy: " ").count > 1 {
    seconWord = fullName.components(separatedBy: " ")[1]
}      
self.institutionNameLabel.text = fullName
if let idEnte = model.institution?.idEnte {
    self.subtitleLable.text = "\(idEnte)"
}
let a = firstWord.first ?? "N"
let b = seconWord.first ?? "N"
self.initialsRoundLabel.text = "\(a)\(b)"

【问题讨论】:

  • 对!如此简单干净!谢谢!如果您想添加答案,我可以签名为已解决

标签: swift string filter


【解决方案1】:

仅从fullName 获取超过 2 的单词,您可以这样做

let words = fullName.components(separatedBy: " ").filter { $0.count > 2}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 2014-01-26
    • 2022-12-10
    • 2022-01-09
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多