-4

I have the code to find out substring from string in Swift, Please help !

My codes to find substring http://corbpl.com/groupinfo.php?show=95 is :-

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))
shubham mishra
  • 971
  • 1
  • 13
  • 32

3 Answers3

3

You should keep your original Objective-C code to tell what you want to do. (I mean your post should contain both the original code, and what you have done till now.)

And your input String should be like this as a String literal:

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

In 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
}

In 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
}

Some points: (using Swift 2 terminology)

  • The rangeOfString(_:) method of Swift String returns Range<String.Index>, not NSRange. You cannot assign the result into a variable of NSRange.

  • The startIndex of the returned Range points to the first character found, the endIndex of the returned Range points to the next to the last character found.

  • The rangeOfString(_:options:range:locale:) method (seemingly rangeOfString(_:range:) in the code above) is better for searching a string within some limited range, than creating a substring.

OOPer
  • 47,149
  • 6
  • 107
  • 142
3

Try this,

   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: "")
Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
2

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)

Output :

http://corbpl.com/groupinfo.php?show=95
Anupam Mishra
  • 3,408
  • 5
  • 35
  • 63