【问题标题】:How to extract phrase from string using Range? [duplicate]如何使用范围从字符串中提取短语? [复制]
【发布时间】:2016-06-12 18:50:46
【问题描述】:

这听起来很容易,但我很难过。 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))

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    最简单和最好的方法是使用NSURL,我包括了如何使用split 和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"
    

    【讨论】:

      【解决方案2】:

      你也可以使用substringFromIndex

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

      但我更喜欢NSURL 方式。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 我误解了这个问题:(
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-02
        相关资源
        最近更新 更多