2017-09-26 23 views
0

這是使用示例代碼從官方Swift4 DOC如何在Swift 4中獲取特定範圍的子字符串?

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個單詞在將來用得更好?

回答

3

您可以使用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]) 
+0

不好意思啊,我應該更清楚。我想要的是「There」這個詞。從Java背景中,我只是將字符串推入字符串數組並從索引7至11打印。Swift4中是否沒有使用子字符串成員的內置方式? –

+0

@KentW試試這個尺寸。 –

+0

謝謝!我不想導入基礎。徹底的答案。我無法在Swift 4 iBook中找到它。 –

0

老習慣很難消退。我用「Java」的方法做了,並且用空格分割了字符串,然後訪問了第二個單詞。

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

您是否注意到這是我在編輯的答案中寫的內容之一? –

1

對於swift4,

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