Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize each word in a string using Swift iOS

Tags:

ios

swift

Is there a function to capitalize each word in a string or is this a manual process?

For e.g. "bob is tall" And I would like "Bob Is Tall"

Surely there is something and none of the Swift IOS answers I have found seemed to cover this.

like image 404
Christopher Wade Cantley Avatar asked Mar 25 '15 16:03

Christopher Wade Cantley


People also ask

How do you capitalize a string in Swift?

To convert a String to Uppercase in Swift, use String. uppercased() function. Call uppercased() function on the String. The function returns a new string with the contents of the original string transformed to uppercase alphabets.

How do you capitalize every word in a string?

Use title() to capitalize the first letter of each word in a string in python. Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.


2 Answers

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.

like image 147
James Webster Avatar answered Sep 18 '22 19:09

James Webster


Swift 3:

var lowercased = "hello there"  var stringCapitalized = lowercased.capitalized //prints:  "Hello There" 
like image 28
Josh O'Connor Avatar answered Sep 17 '22 19:09

Josh O'Connor