如何将字符串格式更改为缩写?

How to change string format to abbreviation?

我有一个 API 那个 returns 的字符串,我想改变这些字符串的格式,以便所有的单词都转换为它们的第一个字母 + "."除了最后一个词保持不变。例如,"United States of America" -----> "U. S. America" 或 "Real Madrid" ------> "R. Madrid" 。有人可以帮忙吗?谢谢。

您可以使用 components(separatedBy: String) 根据字符串之间的空格将每个字符串分隔成字符串数组:

var str = "United States of America"

print(str.components(separatedBy: " ")) // Outputs ["United", "States", "of", "America"]

然后遍历此数组,根据需要修改每个单词并将结果附加到变量 resultString。在您的情况下,您可能只想获取不属于预定义组(例如 "of"、"and" 等)的任何单词的第一个字母,将其设为大写(调用大写()),将其与“。”连接起来并将其附加到您的字符串。当您到达数组的最后一个元素时,只需按原样附加单词。

您可以在开发人员参考中找到更多信息:https://developer.apple.com/reference/swift/string

希望对您有所帮助。一切顺利。

  • 将您的字符串分隔成单词数组(由 " " 分隔)
  • 对于这些词,可能会过滤掉介词和连词(根据您U.S的例子)
  • 对除最后一个单词以外的所有单词执行首字母截断
  • 最后,将截断的单词列表与彼此和最后一个(未截断的)单词连接起来。

例如:

import Foundation

// help function used to fix cases where the places 
// words are not correctly uppercased/lowercased
extension String {
    func withOnlyFirstLetterUppercased() -> String {
        guard case let chars = self.characters,
            !chars.isEmpty else { return self }
        return String(chars.first!).uppercased() + 
            String(chars.dropFirst()).lowercased()
    }
}

func format(placeString: String) -> String {
    let prepositionsAndConjunctions = ["and", "of"]
    guard case let wordList = placeString.components(separatedBy: " ")
        .filter({ !prepositionsAndConjunctions.contains([=10=].lowercased()) }),
        wordList.count > 1 else { return placeString }

    return wordList.dropLast()
        .reduce("") { [=10=] + String(.characters.first ?? Character("")).uppercased() + "." } +
        " " + wordList.last!.withOnlyFirstLetterUppercased()
}

print(format(placeString: "United States of America")) // "U. S. America"
print(format(placeString: "uniTED states Of aMERIca")) // "U. S. America"
print(format(placeString: "Real Madrid"))              // "R. Madrid"
print(format(placeString: "Trinidad and Tobago"))      // "T. Tobago"
print(format(placeString: "Sweden"))                   // "Sweden"

如果您知道要正确格式化您的原始位置字符串 w.r.t。大写和小写,那么您可以通过例如将上面的解决方案修改为不那么冗长的解决方案删除 String 扩展中的帮助方法。