How to change the format of the string in abbreviation?

advertisements

I have an API that returns strings, I want to change the format of these strings so that all the words are converted to their first letter + "." except for the last word wich stays the same . For example, "United States of America" -----> "U. S. America" or "Real Madrid" ------> "R. Madrid" . Can anyone help please? thank you.


  • Separate your string into and array of words (separated by " ")
  • For these words, possibly filter out prepositions and conjunctions (based on your example of U.S.)
  • Perform first-letter truncation of all but the last word
  • Finally, join truncated list of words with eachother and the last (non-truncated) word.

E.g.:

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($0.lowercased()) }),
        wordList.count > 1 else { return placeString }

    return wordList.dropLast()
        .reduce("") { $0 + String($1.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"

If you know your original places strings to be correctly formatted w.r.t. upper & lower case, then you can modify the solution above to a less verbose one by e.g. removing the help method in the String extension.