1 Reply
      Latest reply on Dec 30, 2015 7:07 PM by OOPer
      VolmDev Level 1 Level 1 (0 points)

        Could someone please helpe with the following.  I am trying to extract a string from a string.

         

        I have the following url: https://api.github.com/gists/public?page=2

         

        How can I cut the portion of the string "?page=2" and store it in a variable so that I would have two parts.

         

        var strBase = https://api.github.com/gists/public"

         

        and the page part

         

        var strPage = "?page=2".

         

        Thanks you.

         

        Dave.

        • Re: Question on extracting a substring from a url
          OOPer Level 8 Level 8 (5,715 points)

          Just as a String manipulation:

          var urlStr = "https:...?page=2"
          var strBase: String
          var strPage: String
          if let qIndex = urlStr.characters.indexOf("?") {
              strBase = urlStr.substringToIndex(qIndex)
              strPage = urlStr.substringFromIndex(qIndex)
          } else {
              strBase = urlStr
              strPage = ""
          }
          

          Or this is another way preferred by many:

          let parts = urlStr.componentsSeparatedByString("?")
          strBase = parts[0]
          strPage = parts.count >= 2 ? "?" + parts[1] : ""
          

           

          But if you want manipulate it as URL rather than String, you better consider adopting NSURLComponents.

          if let urlCompo = NSURLComponents(string: urlStr) {
              strPage = urlCompo.query != nil ? "?" + urlCompo.query! : ""
              urlCompo.query = nil
              strBase = urlCompo.string!
          } else {
              fatalError("invalid URL")
          }