[英]How to get substring with specific ranges in Swift 4?
這是使用來自官方 Swift4 文檔的示例代碼
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!"
我只想檢索這句話中的第二個單詞(子字符串)? 所以我只想要“那里”這個詞。
我試過使用“世界!” 作為像let endOfSentence = greeting.index(of: "world!")!
但 Swift 4 Playground 不喜歡那樣。 它期待 'Character' 而我的參數是一個字符串。
那么我怎樣才能得到一個非常精確的子范圍的子字符串呢? 或者在句子中獲得第 n 個單詞以備將來更多使用?
對於swift4,
let string = "substring test"
let start = String.Index(encodedOffset: 0)
let end = String.Index(encodedOffset: 10)
let substring = String(string[start..<end])
您可以使用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])
第一個答案中有一個錯誤。
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"
}
舊習難改。 我用“Java”方式做了它並用空格分割了字符串,然后訪問了第二個字。
print(greeting.split(separator: " ")[1]) // "there /n"
在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])
打印 - >很高興見到你!
我使用的最簡單的方法是:
String(Array(seed)[2...4])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.