Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring with specific ranges in Swift 4?

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?

like image 337
Kent Wong Avatar asked Sep 26 '17 05:09

Kent Wong


People also ask

How do I substring a string in Swift?

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.)

How do I split a string in Swift 4?

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+?

What is range of string?

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.


1 Answers

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])
like image 175
Charles Srstka Avatar answered Oct 13 '22 13:10

Charles Srstka