UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: How to capitalize the first letter of a string all sentences

Forums > SwiftUI

It's example for one sentense: https://www.hackingwithswift.com/example-code/strings/how-to-capitalize-the-first-letter-of-a-string

If I use this code for let test = "the rain in Spain.the rain in Spain.", output is: The rain in Spain.the rain in Spain. I want to get two capitalize the first letter of all sentences + with new line, for example: The rain in Spain. The rain in Spain.

Can you help me, please? Thanks for any answer.

2      

you are going to have to break up the string, capitalize the first letter, and re-join it. Here is a fairly brute force method

func capitalise(_ string:String) -> String {
    let sentences = string.components(separatedBy: ".")
    var capitalisedSentences:[String] = [String]()
    for sentence in sentences {
        let trim = sentence.trimmingCharacters(in: .whitespaces)
        let capitalisedStr = trim.capitalizingFirstLetter()
        print(capitalisedStr)
        capitalisedSentences.append(capitalisedStr)
    }

    return capitalisedSentences.joined(separator: ". ")
}

trimmingCharacters(in...) removed white space at the beginning and end of a string. The join adds back the full stop and space.

Heres a version using map

func capitaliseFilter(_ string:String) -> String {
    var sentences = string.components(separatedBy: ".")
    sentences = sentences.map {
        $0.trimmingCharacters(in: .whitespaces).capitalizingFirstLetter()
    }
    return sentences.joined(separator: ". ")
}

3      

Thank you!

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.