If we have, for example, situation like this:
var myString = "Today was a good day"
What is the best way to return the first word, which is "Today"? I think mapping should be applied, but not sure how.
Thanks.
Use the startIndex property to access the position of the first Character of a String . The endIndex property is the position after the last character in a String . As a result, the endIndex property isn't a valid argument to a string's subscript. If a String is empty, startIndex and endIndex are equal.
The swift string class does not provide the ability to get a character at a specific index because of its native support for UTF characters. The variable length of a UTF character in memory makes jumping directly to a character impossible. That means you have to manually loop over the string each time.
To get the last character of a string, we can use the string. last property in Swift. Similarly, we can also use the suffix() method by passing 1 as an argument to it. The suffix() method can also be used to get the last n characters from a string.
The simplest way I can think of is
let string = "hello world"
let firstWord = string.components(separatedBy: " ").first
let string = "hello world"
let firstWord = string.componentsSeparatedByString(" ").first
and if you think you need to use it a lot in your code, make it as an extension
extension String {
func firstWord() -> String? {
return self.components(separatedBy: " ").first
}
}
let string = "hello world"
let firstWord = string.firstWord()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With