allocate
allocate

Reputation: 1343

Find and replace multiple occurrences of a word in a long string

I'm parsing through some HTML files and tagging while I write the markdown.

For a simplified example:

var String = "This is a text <int=8-10, This is some more text.><int=1-7, This is some alt text.>"

Let's say for starters I want to match every <int= in this string and remove it. Is there an efficient way to do this in Swift right now?

Upvotes: 1

Views: 1445

Answers (3)

Pigpocket
Pigpocket

Reputation: 458

For your information, this function is now called:

replacingOccurrences(of: String, with: String, options: String.CompareOptions, range: Range<String.Index>?)

Upvotes: 0

Naloiko Eugene
Naloiko Eugene

Reputation: 2626

Here is a method to get ranges of substrings as an array:

(
    "NSRange: {538, 1}",
    "NSRange: {848, 1}",
    "NSRange: {1183, 1}",
    "NSRange: {1418, 1}"
)

func rangesOfString(searchString: String,  attrStr : NSMutableAttributedString) -> NSArray
    {
        var inputLength = count(attrStr.string)
        var searchLength = count(searchString)
        var range = NSRange(location: 0, length: attrStr.length)

        var results = NSMutableArray()
        while (range.location != NSNotFound) {
            range = (attrStr.string as NSString).rangeOfString(searchString, options: nil, range: range)
            if (range.location != NSNotFound) {
                results.addObject(NSRange(location: range.location, length: searchLength))
                range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
            }
        }
        return results as NSArray
    }

Upvotes: 1

J&#233;r&#244;me
J&#233;r&#244;me

Reputation: 8066

myString.stringByReplacingOccurrencesOfString("<int=", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

stringByReplacingOccurrencesOfString (documentation) will replace a substring with another substring (in this case empty "").

Upvotes: 3

Related Questions