2016-06-12 11 views
-1

これは簡単ですが、私は困惑しています。 Rangeの構文と機能は私にとって非常に混乱しています。Rangeを使って文字列からフレーズを抽出するには?

私はこのようなURLがあります。私は、文字列の末尾に一部#global-best-time-to-post、本質的#を抽出する必要が

https://github.com/shakked/Command-for-Instagram/blob/master/Analytics%20Pro.md#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

私は誤解しました質問 :( –

関連する問題