如何在Swift 4中获取具有特定范围的子字符串?

Ken*_*ong 9 substring swift swift4

这是使用官方Swift4文档中的示例代码

let greeting = "Hi there! It's nice to meet you! "
let endOfSentence = greeting.index(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"
Run Code Online (Sandbox Code Playgroud)

但是,让我们说let greeting = "Hello there world!" ,我想在这句话中只检索第二个单词(substring)?所以我只想要"那里"这个词.

我试过用"世界!" 作为一个参数, let endOfSentence = greeting.index(of: "world!")!但Swift 4 Playground并不喜欢这样.它期待'Character',我的论点是一个字符串.

那么如何才能得到一个非常精确的子范围的子串呢?或者在句子中加上第n个单词以便将来使用?

Kri*_*ofe 16

对于swift4,

let string = "substring test"
let start = String.Index(encodedOffset: 0)
let end = String.Index(encodedOffset: 10)
let substring = String(string[start..<end])
Run Code Online (Sandbox Code Playgroud)


Cha*_*tka 11

您可以使用搜索子字符串range(of:).

import Foundation

let greeting = "Hello there world!"

if let endIndex = greeting.range(of: "world!")?.lowerBound {
    print(greeting[..<endIndex])
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello there 
Run Code Online (Sandbox Code Playgroud)

编辑:

如果你想分开单词,那就是快速而肮脏的方式和好方法.快速而肮脏的方式:

import Foundation

let greeting = "Hello there world!"

let words = greeting.split(separator: " ")

print(words[1])
Run Code Online (Sandbox Code Playgroud)

这是彻底的方法,它将枚举字符串中的所有单词,无论它们如何分开:

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])
Run Code Online (Sandbox Code Playgroud)

编辑2:如果你只是想要获得第7个到第11个角色,你可以这样做:

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])
Run Code Online (Sandbox Code Playgroud)


kth*_*rat 6

在 Swift 5 中,已弃用 encodingOffset (swift 4 func)。
您将需要使用utf160Offset

// Swift 5     

let string = "Hi there! It's nice to meet you!"
let startIndex = 10 // random for this example
let endIndex = string.count

let start = String.Index(utf16Offset: startIndex, in: string)
let end = String.Index(utf16Offset: endIndex, in: string)

let substring = String(string[start..<end])
Run Code Online (Sandbox Code Playgroud)

打印 -> 很高兴认识你!