This is using the example code from the official Swift4 doc
let greeting = "Hi there! It's nice to meet you! 👋"
let endOfSentence = greeting.index(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"
But lets say let greeting = "Hello there world!"
and I want to retrieve only the second word (substring) in this sentence? So I only want the word "there".
I've tried using "world!" as an argument like
let endOfSentence = greeting.index(of: "world!")!
but Swift 4 Playground doesn't like that. It's expecting 'Character' and my argument is a string.
So how can I get a substring of a very precise subrange? Or get nth word in a sentence for greater use in the future?
You can get a substring from a string by using subscripts or a number of other methods (for example, prefix , suffix , split ). You still need to use String. Index and not an Int index for the range, though. (See my other answer if you need help with that.)
Xcode 8.1 / Swift 3.0.1 Attention (Swift 4): If you have a string like let a="a,,b,c" and you use a. split(separator: ",") you get an array like ["a", "b", c"] by default. This can be changed using omittingEmptySubsequences: false which is true by default. Any multi-character splits in Swift 4+?
string range string first last. Returns a range of consecutive characters from string, starting with the character whose index is first and ending with the character whose index is last. An index of 0 refers to the first character of the string. first and last may be specified as for the index method.
You can search for substrings using range(of:)
.
import Foundation
let greeting = "Hello there world!"
if let endIndex = greeting.range(of: "world!")?.lowerBound {
print(greeting[..<endIndex])
}
outputs:
Hello there
EDIT:
If you want to separate out the words, there's a quick-and-dirty way and a good way. The quick-and-dirty way:
import Foundation
let greeting = "Hello there world!"
let words = greeting.split(separator: " ")
print(words[1])
And here's the thorough way, which will enumerate all the words in the string no matter how they're separated:
import Foundation
let greeting = "Hello there world!"
var words: [String] = []
greeting.enumerateSubstrings(in: greeting.startIndex..<greeting.endIndex, options: .byWords) { substring, _, _, _ in
if let substring = substring {
words.append(substring)
}
}
print(words[1])
EDIT 2: And if you're just trying to get the 7th through the 11th character, you can do this:
import Foundation
let greeting = "Hello there world!"
let startIndex = greeting.index(greeting.startIndex, offsetBy: 6)
let endIndex = greeting.index(startIndex, offsetBy: 5)
print(greeting[startIndex..<endIndex])
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