Capitalize each first letter of the words in a string [duplicate] - ios

This question already has answers here:
How to capitalize each word in a string using Swift iOS
(8 answers)
Closed 5 years ago.
How can i capitalized each first letter of the result of this
self.namE.text = currentUser.displayName
self.handle.text = snapshotValue?["handle"] as? String
instead of "Bruce willis" i would like to have "Bruce Willis", i created this extension to capitalized the first letter
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + dropFirst()
}
}
but it obviously capitalize only the first word in a string, so how i have to modify this extension to get the right result? ( i looked in the doc but i didn't understand very well )

String in swift4 has already a capitalized computed property on itself, so without implementing anything yourself, you can get the desired result using this:
self.namE.text = currentUser.displayName.capitalized
E.g.:
self.namE.text = "bruce willis".capitalized

Related

Swift split String into array [duplicate]

This question already has answers here:
Swift Put String to Array from one to all letters
(5 answers)
Closed 2 years ago.
I have a string with no spaces I would like to turn the string into an array.
Let's say the string is "guru1", I would like my array to be ["g", "gu", "gur", "guru", "guru1"]
Thanks in advance.
You can use reduce :
"guru1".reduce([]) { $0 + [($0.last ?? "") + "\($1)"] }

Find out if a Swift string contains emoji [duplicate]

This question already has answers here:
Find out if Character in String is emoji?
(17 answers)
Closed 5 years ago.
I am working in an application in which i need to look up emoji characters from the string means a string contains one or more emojis ? As i am new in swift so i am not aware about it.
exa. "Newbie 😀" will returns yes and
"Newbie" will returns no
Yes please use below method to identify emojies
public var checkcontainEmoji: Bool
{
for ucode in unicodeScalars
{
switch ucode.value
{
case 0x3030, 0x00AE, 0x00A9,
0x1D000...0x1F77F,
0x2100...0x27BF,
0xFE00...0xFE0F,
0x1F900...0x1F9FF:
return true
default:
continue
}
}
return false
}
Output : - "HI 😀".checkcontainEmoji --> TRUE

Swift 2 query printing with Optional wording [duplicate]

This question already has answers here:
swift How to remove optional String Character
(14 answers)
Closed 6 years ago.
let username = self.user?.getProperty("username") as? String
self.navigationItem.title = "#\(username)"
What I want to happen there is for it to print on the screen that users username with an # in front of it like #user2
What it is printing instead is #Optional("user2")
How do I make this stop that? Ha
String Interpolation prints also literal Optional(...) if the value is an optional.
To avoid that use either optional binding
if let username = self.user?.getProperty("username") as? String {
self.navigationItem.title = "#\(username)"
}
Or the ternary conditional operator
let username = self.user?.getProperty("username") as? String
self.navigationItem.title = username != nil ? "#\(username!)" : ""
In the first example the title won't be updated if username is nil, in the second it's updated with an empty string.

How to capitalize each word in a string using Swift iOS

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.
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.
Swift 3:
var lowercased = "hello there"
var stringCapitalized = lowercased.capitalized
//prints: "Hello There"
Since iOS 9 a localised capitalization function is available as capitalised letters may differ in languages.
if #available(iOS 9.0, *) {
"istanbul".localizedCapitalizedString
// In Turkish: "Ä°stanbul"
}
An example of the answer provided above.
var sentenceToCap = "this is a sentence."
println(sentenceToCap.capitalizedStringWithLocale(NSLocale.currentLocale()) )
End result is a string "This Is A Sentence"
For Swift 3 it has been changed to capitalized .
Discussion
This property performs the canonical (non-localized) mapping. It is suitable for programming operations that require stable results not depending on the current locale.
A capitalized string is 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. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart(_:end:contentsEnd:for:)). Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercased for an example.
There is a built in function for that
nameOfString.capitalizedString
This will capitalize every word of string. To capitalize only the first letter you can use:
nameOfString.replaceRange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalizedString)
Older Thread
Here is what I came up with that seems to work but I am open to anything that is better.
func firstCharacterUpperCase(sentenceToCap:String) -> String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = sentenceToCap.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
or if I want to use this as an extension of the string class.
extension String {
var capitalizeEachWord:String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = self.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
}
Again, anything better is welcome.
Swift 5 version of Christopher Wade's answer
let str = "my string"
let result = str.capitalized(with: NSLocale.current)
print(result) // prints My String

concatenate enum of strings [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have 2 enums below.
CONFIG_URLS.BASE_URL
CONFIG_URLS.URL1
Each of these enums points to a string.
I want to create a string variable by concatenating BASE_URL and URL1.
Should be swift code.
Can anybody help? Many thanks
I presume that your enum has a raw value of type string. In that case, I would recommend creating a static function that given a enum case returns an absolute URL obtained by appending the value of a case representing a path to the value of the base url:
enum CONFIG_URLS : String {
case BASE_URL = "http://www.myurl.com"
case URL1 = "/some/path"
static func getUrl(url: CONFIG_URLS) -> String {
switch url {
case .BASE_URL:
return BASE_URL.rawValue
default:
return "\(CONFIG_URLS.BASE_URL.rawValue)\(url.rawValue)"
}
}
}
println(CONFIG_URLS.getUrl(.BASE_URL))
println(CONFIG_URLS.getUrl(.URL1))
Alternatively, the static method can be converted to a property, used in a similar way:
enum CONFIG_URLS : String {
case BASE_URL = "http://www.myurl.com"
case URL1 = "/some/path"
var url: String {
switch self {
case .BASE_URL:
return BASE_URL.rawValue
default:
return "\(CONFIG_URLS.BASE_URL.rawValue)\(self.rawValue)"
}
}
}
println(CONFIG_URLS.BASE_URL.url)
println(CONFIG_URLS.URL1.url)
Swift provides the following options.
Option 1
You can concatenate two constant strings as below:
let str1 = "hi" // constant
let str2 = " how are u" // constant
var str3 = string1 + string2 // here str3 is variable which will hold
// the concatenated value i.e. str3 = "hi how are u"
Option 2
You can also append a String value to an existing String variable with the addition assignment operator (+=):
let str1 = "hi"
var str2 = "how are u"
str2 += str1
// str2 now equals "hi how are u"
THe solution was to use rawValue and use + for concatenation (in Swift) , which I wasnt aware about regarding enums.
Thanks everyone.

Resources