Question on extracting a substring from a url

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.

Accepted Reply

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

Replies

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