TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.