2016-06-12 2 views
-1

쉽게 들리지만 나는 혼란 스럽습니다. Range의 구문과 함수는 매우 혼란 스럽습니다.범위를 사용하여 문자열에서 구문을 추출하는 방법은 무엇입니까?

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

내가 문자열의 끝 부분 #global-best-time-to-post, 본질적으로 #를 추출해야합니다

나는이 같은 URL이 있습니다.

urlString.rangeOfString("#") 반환 Range 은 그 때 나는 advanceBy(100)를 호출하면 바로 문자열의 끝으로 이동하지만, 대신 충돌 것이라고 가정이 일을 시도했다.

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" 

답변

4

과이 작업을 수행하는 가장 좋은 방법은 NSURL을 사용하여, 나는 splitrangeOfString으로 작업을 수행하는 방법을 포함 방법은 NSURL을 선호합니다.

1

또한 substringFromIndex

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

하지만 난을 사용할 수

가장 쉬운
hashtag = urlString.substringWithRange(range.startIndex...range.endIndex.advancedBy(100)) 
-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

내가 오해 질문 :( –

관련 문제