2016-06-12 21 views
-1

Das klingt einfach, aber ich bin ratlos. Die Syntax und Funktionen von Range sind sehr verwirrend für mich.Wie extrahiere ich eine Phrase aus der Zeichenkette mit Range?

Ich habe eine URL wie folgt aus:

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

ich das Teil #global-best-time-to-post, im Wesentlichen die # bis zum Ende des Strings extrahieren müssen.

urlString.rangeOfString("#") kehrt Range Dann habe ich versucht dies, dass advanceBy(100) nur bis zum Ende des Strings gehen würde Aufruf unter der Annahme zu tun, sondern stürzt.

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

Antwort

4

einfachste und beste Weg, dies zu tun ist, NSURL verwenden, inklusive ich, wie es zu tun mit split und rangeOfString:

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

Sie auch substringFromIndex

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

aber ich verwenden könnte bevorzuge die NSURL Weise.

-1

Verwendung componentsSeparatedByString Methode

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

Ihre gewünschte letzte Textphrase (ohne # char) auf dem letzten Index der splitArray sein wird, können Sie das # mit Ihrem Ausdruck verketten

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

ich falsch verstanden die Frage :( –

Verwandte Themen