查找并替换长字符串中多个单词的出现次数

时间:2015-02-12 19:25:09

标签: swift

我在编写降价时解析了一些HTML文件和标记。

简化示例:

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

让我们首先说我要匹配此字符串中的每个<int=并将其删除。现在有没有一种有效的方法在Swift中做到这一点?

2 个答案:

答案 0 :(得分:3)

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

stringByReplacingOccurrencesOfStringdocumentation)会将子字符串替换为另一个子字符串(在本例中为空"")。

答案 1 :(得分:1)

以下是将子字符串范围作为数组获取的方法:

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