Swift Apply .Uppercasestring to Only the First Letter of a String

Swift apply .uppercaseString to only the first letter of a string

Including mutating and non mutating versions that are consistent with API guidelines.

Swift 3:

extension String {
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}

mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}

Swift 4:

extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}

mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}

SwiftUI - Capitalise first letter

Any Swift (NS)String API can be used also in SwiftUI

Text("hello world".capitalized)

How to capitalize the first character of sentence using Swift

import Foundation

// A lowercase string
let description = "the quick brown fox jumps over the lazy dog."

// The start index is the first letter
let first = description.startIndex

// The rest of the string goes from the position after the first letter
// to the end.
let rest = advance(first,1)..
// Glue these two ranges together, with the first uppercased, and you'll
// get the result you want. Note that I'm using description[first...first]
// to get the first letter because I want a String, not a Character, which
// is what you'd get with description[first].
let capitalised = description[first...first].uppercaseString + description[rest]

// Result: "The quick brown fox jumps over the lazy dog."

You may want to make sure there's at least one character in your sentence before you start, as otherwise you'll get a runtime error trying to advance the index beyond the end of the string.

Convert string that is all caps to only only having first letter of each word caps

Apple already did that for you:

print("HELLO WORLD".capitalized)

Documentation: https://developer.apple.com/documentation/foundation/nsstring/1416784-capitalized

Add a space in a String after the first letter - Swift 5

var greeting = "Hello, playground"
greeting.insert(" ", at: greeting.index(after: greeting.startIndex))
print(greeting) // H ello, playground
greeting.insert(" ", at: greeting.index(greeting.startIndex, offsetBy: 1))
print(greeting) // H ello, playground

How to lowecase only first word in the sentence?

Get first letter of the first word and make it lowercase , then remove first letter and add the rest.

extension StringProtocol {
var lowerCaseFirts: String { prefix(1).lowercased() + dropFirst() }
}

let str = "Hello World"
print(str.lowerCaseFirts)


Related Topics



Leave a reply



Submit