从Swift中的string子string

我有代码从string中find子string,请帮助!

我的代码来查找子stringhttp://corbpl.com/groupinfo.php?show=95是: –

 var aString: String = "href=http://www.corpbpl.com/groupinfo.php?show=95 onmousedown=uaction(this,{up:'90de%=%Nofi7rO6B&l=8upb1p&E%=6&ex=jXTDh5zYQLa9&});" var hashtag: NSRange = aString.rangeOfString("http://") var word: NSRange = aString.substringFromIndex(aString.startIndex.advancedBy(hashtag.location)) 

你应该保留原来的Objective-C代码来告诉你想要做什么。 (我的意思是你的文章应该包含原始代码,以及到目前为止所做的工作。)

而你的inputstring应该像这样一个string文字:

 var aString = "href=\"http://www.corpbpl.com/groupinfo.php?show=95\" onmousedown=\"uaction(this,{up:'90de%=%Nofi7rO6B&l=8upb1p&E%=6&ex=jXTDh5zYQLa9&})\"" 

在Swift 2中:

 if let hashtag = aString.rangeOfString("http://"), word = aString.rangeOfString("95", range: hashtag.startIndex..<aString.endIndex) { let hashtagWord = aString[hashtag.startIndex..<word.endIndex] print(hashtagWord) //->http://www.corpbpl.com/groupinfo.php?show=95 } 

在Swift 3:

 if let hashtag = aString.range(of: "http://"), let word = aString.range(of: "95", range: hashtag.lowerBound..<aString.endIndex) { let hashtagWord = aString[hashtag.lowerBound..<word.upperBound] print(hashtagWord) //->http://www.corpbpl.com/groupinfo.php?show=95 } 

有些观点(使用Swift 2术语)

  • Swift String的rangeOfString(_:)方法返回Range<String.Index> ,而不是NSRange 。 您不能将结果分配给NSRange的variables。

  • 返回的RangestartIndex指向find的第一个字符,返回的RangeendIndex指向find的最后一个字符的下一个。

  • rangeOfString(_:options:range:locale:)方法(在上面的代码中看起来rangeOfString(_:range:) )更适合在一定范围内searchstring,而不是创build子string。

Swift 2.x

 var aString = "href=http://www.corpbpl.com/groupinfo.php?show=95 onmousedown=uaction(this,{up:'90de%=%Nofi7rO6B&l=8upb1p&E%=6&ex=jXTDh5zYQLa9&});" var hashtag = aString.rangeOfString("http://") var word = aString.rangeOfString("95") var hashtagWord = aString.substringWithRange(Range<String.Index>(start: hashtag!.startIndex.advancedBy(0), end: word!.endIndex.advancedBy(0))) print(hashtagWord) 

输出:

 http://corbpl.com/groupinfo.php?show=95 

尝试这个,

  let aString: String = "href=http://www.corpbpl.com/groupinfo.php?show=95 onmousedown=uaction(this,{up:'90de%=%Nofi7rO6B&l=8upb1p&E%=6&ex=jXTDh5zYQLa9&});" var arr = aString.componentsSeparatedByString(" ") let newStr = arr[0] as String var resultStr = newStr.stringByReplacingOccurrencesOfString("href=", withString: "")