How to Capitalize Each Word in a String Using Swift iOS

How to capitalize each word in a string using Swift iOS

Are you looking for capitalizedString

Discussion

A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.

and/or capitalizedStringWithLocale(_:)

Returns a capitalized representation of the receiver using the specified locale.

For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.

Trying to capitalize the first letter of each word in a text field Using Swift

Simply set Textfield's Capitalization for words.

Sample Image

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()
}
}

How to capitalize first word in every sentence with Swift

You can use Regular Expressions to achieve this. I'm adding this function as a String extension so it will be trivial to call in the future:

extension String {

func toUppercaseAtSentenceBoundary() -> String {
var string = self.lowercaseString

var capacity = string.utf16Count
var mutable = NSMutableString(capacity: capacity)
mutable.appendString(string)

var error: NSError?

if let regex = NSRegularExpression(
pattern: "(?:^|\\b\\.[ ]*)(\\p{Ll})",
options: NSRegularExpressionOptions.AnchorsMatchLines,
error: &error
) {

if let results = regex.matchesInString(
string,
options: NSMatchingOptions.allZeros,
range: NSMakeRange(0, capacity)
) as? [NSTextCheckingResult] {

for result in results {
let numRanges = result.numberOfRanges
if numRanges >= 1 {
for i in 1.. let range = result.rangeAtIndex(i)
let substring = mutable.substringWithRange(range)
mutable.replaceCharactersInRange(range, withString: substring.uppercaseString)
}
}
}
}
}

return mutable
}
}

var string = "someSentenceWith UTF text İŞğĞ. anotherSentenceğüÜğ.".toUppercaseAtSentenceBoundary()

How to capitalize first word in every sentence with Swift 3?

Is this what you're after?

Each sentence is iterated. For the first word in each sentence, if it contains a capital letter, nothing changes, otherwise, it is capitalized and the rest of the sentence is appended to the result.

let str = "this is a sentence without a brand named tablet. this too is a sentence but with iPad in it! iPad at start of sentence here?"
var result = ""

//Iterate each sentence
str.uppercased().enumerateSubstrings(in: str.startIndex ..< str.endIndex, options: .bySentences) { substring, range, _, _ in

var original = str.substring(with: range)

var capitalize = true

//Iterate each word in the sentence
substring!.enumerateSubstrings(in: substring!.startIndex ..< substring!.endIndex, options: .byWords) { word, wordRange , _ , stop in

var originalWord = original.substring(with: wordRange)

//If there is a capital letter in that word, don't capitalize it
for character in originalWord.characters {
if String(character).uppercased().characters.first == character {
capitalize = false
break
}
}

//But always stop after the first word. It's the only one of concern
stop = true
}


//Modify the first word if needed
if capitalize {
result += String(original.characters.prefix(1)).uppercased()
result += String(original.characters.dropFirst(1))
}
else {
result += original
}

}
print(result)

outputs:

This is a sentence without a brand named tablet. This too is a sentence but with iPad in it! iPad at start of sentence here?

NB. I didn't focus on efficiency here. If you are going to use this for a large amount of data, you may want to profile it first!

Note

I don't think the .bySentences option is very robust. During my testing, I accidentally had two spaces in one of the sentences and it failed to parse properly. I've also just tried with your example "Apple..." sentences and it only finds one.

How can I capitalize one word in a UILabel in swift?

I suggest you to add this extension to your code.

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

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

(Form Hacking With Swift)

Also for the UILabel.text property apply a custom function that split each word in string, and apply the capital letter.

An example could be that:

extension String {
func capitalizeWords() -> String {
self.split(separator: " ")
.map({ String($0).capitalizingFirstLetter() })
.joined(separator: " ")
}
}

The complexity could be decreased I think, but it's just a working hint ;)

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.



Related Topics



Leave a reply



Submit