2016-06-12 57 views
-1

這聽起來很簡單,但我很難過。 Range的語法和功能對我來說非常混亂。如何使用Range從字符串中提取短語?

我有這樣一個URL:

https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post 

我需要將部分#global-best-time-to-post,基本上#提取到字符串的結尾。

urlString.rangeOfString("#")返回Range 然後我試圖做這個假設調用advanceBy(100)只想去到字符串的結尾,而是它崩潰。

hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100)) 

回答

4

最簡單,要做到這一點最好的辦法是用NSURL,我包括如何與splitrangeOfString做到這一點:

import Foundation 

let urlString = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post" 

// using NSURL - best option since it validates the URL 
if let url = NSURL(string: urlString), 
    fragment = url.fragment { 
    print(fragment) 
} 
// output: "global-best-time-to-post" 

// using split - pure Swift, no Foundation necessary 
let split = urlString.characters.split("#") 
if split.count > 1, 
    let fragment = split.last { 
    print(String(fragment)) 
} 
// output: "global-best-time-to-post" 

// using rangeofString - asked in the question 
if let endOctothorpe = urlString.rangeOfString("#")?.endIndex { 
    // Note that I use the index of the end of the found Range 
    // and the index of the end of the urlString to form the 
    // Range of my string 
    let fragment = urlString[endOctothorpe..<urlString.endIndex] 
    print(fragment) 
} 
// output: "global-best-time-to-post" 
1

你也可以使用substringFromIndex

let string = "https://github.com..." 
if let range = string.rangeOfString("#") { 
    let substring = string.substringFromIndex(range.endIndex) 
} 

,但我我更喜歡NSURL的方式。

-1

使用componentsSeparatedByString方法

let url = "https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#global-best-time-to-post" 
let splitArray = url.componentsSeparatedByString("#") 

您所需的最後一個文本詞組(不含#字符)將是splitArray的最後索引處,您可以連接#隨你的那句

var myPhrase = "#\(splitArray[splitArray.count-1])" 
print(myPhrase) 
+0

我誤解問題:( –

相關問題