Aymen BRomdhane
Aymen BRomdhane

Reputation: 141

How to change string format to abbreviation?

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 which stays the same.

For example,
"United States of America" -> "U. S. America"
or
"Real Madrid" -> "R. Madrid".

Can anyone help please? thank you.

Upvotes: 0

Views: 1310

Answers (2)

dfrib
dfrib

Reputation: 73206

  • 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.

Upvotes: 1

Marcus
Marcus

Reputation: 2321

You could use components(separatedBy: String) to separate each string into and array of strings based on the whitespace between them:

var str = "United States of America"

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

Then iterate through this array, amending each word as you wish and appending the result to a variable resultString. In your case, you would want to take just the first letter of any word that does not fall within a predefined group (such as "of", "and" etc.), make it uppercase (with a called to uppercased()), concatenate it with "." and append it to your string. When you get to the last element of the array, simply append the word as is.

You can find more at the Developer reference: https://developer.apple.com/reference/swift/string

Hope that helps. All best.

Upvotes: 1

Related Questions