插入字符在string中的特定字符之后:Swift
我有一个Urlstring,我想在符号(=)之后插入减号“ – ”。 我有以下string: –
http://www.corpebl.com/blog.php?show=250
要么
http://www.bdm.com/gm.php?id=2
而我想要下面的string:
http://www.corpebl.com/blog.php?show=-250
要么
http://www.bdm.com/gm.php?id=-2
请尽量避免使用索引计数,因为长度每次都是可变的,所以等于(=)的位置也会每次都不一样。
你可以使用replace = with = – ,通过使用stringByReplacingOccurrencesOfString的概念
let aString: String = "http://www.corpebl.com/blog.php?show=250" let newString = aString.stringByReplacingOccurrencesOfString("=", withString: "=-") print(newString)
你得到的输出像
你应该可以通过replace=
with =-
:
let s = "http://www.corpebl.com/blog.php?show=250" let res = s.stringByReplacingOccurrencesOfString("=", withString: "=-", options: NSStringCompareOptions.LiteralSearch, range: nil)
这在string中有多个等号的情况下是有点危险的。 更精确的方法是定位第一个(或最后一个)等号,然后手动组合生成的string:
let s : NSString = "http://www.corpebl.com/blog.php?show=250" let p = s.rangeOfString("=") if p.location != NSNotFound { let res : String = s.stringByReplacingCharactersInRange(p, withString: "=-") }
NSURLComponents
允许您select性地访问和修改URL的每个部分。 这里有一个例子,即使在多个查询项目列表中,也可以用show=<-num>
replaceshow=<num>
:
var urlString = "http://www.corpebl.com/blog.php?foo&show=250&bar=baz" if var urlComponents = NSURLComponents(string: urlString), var queryItems = urlComponents.queryItems { for (idx, query) in queryItems.enumerate() { if query.name == "show", let val = query.value, let num = Int(val) { queryItems[idx] = NSURLQueryItem(name: query.name, value: String(-num)) } } urlComponents.queryItems = queryItems urlString = urlComponents.string! } print(urlString) // http://www.corpebl.com/blog.php?foo&show=-250&bar=baz
我知道你现在有了一个可行的解决scheme,但是我想我会用一些更一般的东西来形容。
如果您想更多地控制哪些参数附加一个减号,您应该查看NSURLQueryItem
类( 这里logging )。
您可以通过使用NSURLComponents
类( 此处logging )将URL分隔成组件,然后可以访问queryItems
数组。
所以像这样:
if let components = NSURLComponents(string: "http://www.corpebl.com/blog.php?show=250"), let queryItems = components.queryItems { }
会给你一个URL,从你的string拆分成组件,你有一个数组中的查询项目。 现在,您已经准备好查看各个queryItems:
for item in queryItems where item.value != nil { //here you can check on the item.name //and if that matches whatever you need, you can do your magic }
所以,一个函数只会为所有参数添加一个负号,并从中返回一个URLstring,如下所示:
func addMinusToParameters(inURLString urlString: String) -> String? { guard let components = NSURLComponents(string: urlString), let queryItems = components.queryItems else { return nil } var minusItems = [NSURLQueryItem]() for item in queryItems where item.value != nil { minusItems.append(NSURLQueryItem(name: item.name, value: "-\(item.value!)")) } components.queryItems = minusItems guard let minusUrl = components.URL else { return nil } return minusUrl.absoluteString }
举个例子:
if let minusString = addMinusToParameters(inURLString: "http://www.corpebl.com/blog.php?show=250&id=23") { print(minusString) //gives you "http://www.corpebl.com/blog.php?show=-250&id=-23" }
是的,这可能看起来像更多的工作,但我认为它也更灵活。
希望你能用这个。