如何使用Range从字符串中提取短语?

时间:2016-06-12 18:50:46

标签: ios swift

这听起来很容易,但我很难过。 Range的语法和功能对我来说非常困惑。

我有这样的网址:

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))

3 个答案:

答案 0 :(得分: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 :(得分:1)

您也可以使用substringFromIndex

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

但我更喜欢NSURL方式。

答案 2 :(得分:-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("#")

您所需的最后一个短语(没有#char)将位于splitArray的最后一个索引处,您可以将#与您的短语连接

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