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

时间:2017-09-26 05:00:58

标签: swift substring swift4

这是使用官方Swift4 doc

中的示例代码
let greeting = "Hi there! It's nice to meet you! "
let endOfSentence = greeting.index(of: "!")!
let firstSentence = greeting[...endOfSentence]
// firstSentence == "Hi there!"

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

我尝试过使用"世界!"作为一个论点 let endOfSentence = greeting.index(of: "world!")!但是Swift 4 Playground并不是那样的。它期待'字符'我的论点是一个字符串。

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

5 个答案:

答案 0 :(得分:16)

对于swift4,

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

答案 1 :(得分:10)

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

import Foundation

let greeting = "Hello there world!"

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

输出:

Hello there 

编辑:

如果你想分开单词,那么这是一种快速而肮脏的方式和好方法。快速而肮脏的方式:

import Foundation

let greeting = "Hello there world!"

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

print(words[1])

这是彻底的方式,无论他们如何分开,都会列出字符串中的所有单词:

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

编辑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])

答案 2 :(得分:2)

第一个答案有一个错误。

Range<String.Index>.upperBound

upperBound属性应为endIndex 例如:

let text = "From Here Hello World"
if let result = text.range(of: "Hello World") {
     let startIndex = result.upperBound
     let endIndex = result.lowerBound
     print(String(text[startIndex..<endIndex])) //"Hello World"
}

答案 3 :(得分:0)

旧习惯难受。我用“Java”方式做了它,然后用空格分割字符串,然后访问第二个字。

print(greeting.split(separator: " ")[1]) // "there /n"

答案 4 :(得分:-1)

在Swift 5中,encodedOffset(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])

打印->很高兴认识您!