How to prevent capitalizing some of the texts in Swift 5?

Viewed 76

Below is the sample code I need to capitalise. I have achieved by using the "capitalized" method.

var string = "6TH FLOOR BAMBALAPITIYA"
print(string.capitalized)

The result was,

6Th Floor Bambalapitiya

But I do not want the letter T in "6Th Floor" to be capitalised. Please help me to write a common function to achieve,

6th Floor Bambalapitiya

Thank you in advance

2 Answers

try something like this:

func addressCapitalised(_ str: String) -> String {
    var result = str
    let temp1 = str.split(separator: " ")
    if let firstStr = temp1.first  {
        let temp2 = String(firstStr).lowercased()
        let temp3 = temp1.dropFirst().joined(separator: " ").capitalized
        result = (temp2 + " " + temp3).trimmingCharacters(in: .whitespacesAndNewlines)
    }
    return result
}

let myString = "6TH FLOOR BAMBALAPITIYA"
let dasCapital = addressCapitalised(myString)
print("\n----> dasCapital: \(dasCapital) ")
var string = "6TH FLOOR BAMBALAPITIYA"
print(string.lowercased().split(separator: " ").map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined(separator: " "))
// 6th Floor Bambalapitiya

I'll break down the steps of this to be a bit easier to understand.

  1. Lowercase the entire string.
  2. Split the string into an array using " " as a separator.
  3. Iterate through each element of the array using map.
  4. Uppercase the first character of each element and combine the remainder of the element, dropping the first character (since we already have the prefix).
  5. Join the array back together into a string using " ".
Related