How to get substring with specific ranges in Swift 4?
You can search for substrings using range(of:)
.
import Foundationlet 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 Foundationlet 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 Foundationlet 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 Foundationlet greeting = "Hello there world!"let startIndex = greeting.index(greeting.startIndex, offsetBy: 6)let endIndex = greeting.index(startIndex, offsetBy: 5)print(greeting[startIndex..<endIndex])
In Swift 5 encodedOffset (swift 4 func) is deprecated.
You will need to use utf160Offset
// Swift 5 let string = "Hi there! It's nice to meet you!"let startIndex = 10 // random for this examplelet endIndex = string.countlet start = String.Index(utf16Offset: startIndex, in: string)let end = String.Index(utf16Offset: endIndex, in: string)let substring = String(string[start..<end])
prints -> It's nice to meet you!