函数在swift中查找字符串中字符串的所有NSRanges

时间:2015-09-27 08:44:03

标签: swift nsrange

我希望DNA序列中的所有CG字母对都是红色的(字符串)。我可以通过使用NSMutableAttributedString来实现。 为此,我需要所有CG职位的NSRanges,我试图在下面但是在行中

indexesOfStringIn = (stringOut as NSString).rangeOfString(stringIn, options: 0, range: rangeForIndexStringIn) 

带有范围的rangeOfString不能使用类型的参数列表调用(String,options:Int,range:NSRange)。哪里出错?我做错了什么?

func searchForNSRangesOfStringInString(stringOut: String, stringIn: String) -> [NSRange]

{
    var arrayOfindexesOfStringIn = [NSRange]()

if stringIn.characters.count > 1
{
    var rangeNS = (stringOut as NSString).rangeOfString(stringIn)

    if rangeNS.location != NSNotFound
    {
        let endIndexOfStringOut = (stringOut as NSString).length - 1
        var indexesOfStringIn = (stringOut as NSString).rangeOfString(stringIn)
        arrayOfindexesOfStringIn = [indexesOfStringIn]
        var lastIndexOfStringIn = (stringOut as NSString).rangeOfString(stringIn).location
        var rangeForIndexStringIn = NSRange(lastIndexOfStringIn...endIndexOfStringOut)

        while indexesOfStringIn.location != NSNotFound
        {
            indexesOfStringIn = (stringOut as NSString).rangeOfString(stringIn, options: 0, range: rangeForIndexStringIn)

            if indexesOfStringIn.location != NSNotFound
            {

                arrayOfindexesOfStringIn.append(indexesOfStringIn)

                lastIndexOfStringIn = (stringOut as NSString).rangeOfString(stringIn, options: 0, range: rangeForIndexStringIn).location

                rangeForIndexStringIn = NSRange(lastIndexOfStringIn...endIndexOfStringOut)

            }
        }
    }
}
return arrayOfindexesOfStringIn
} 

1 个答案:

答案 0 :(得分:2)

正如uchuugaka所建议的那样,使用NSRegularExpression更容易返回字符串中匹配范围的数组,如下所示:

extension String {
    func findOccurencesOf(text text:String) -> [NSRange] {
        return !text.isEmpty ? try! NSRegularExpression(pattern: text, options: []).matchesInString(self, options: [], range: NSRange(0..<characters.count)).map{ $0.range } : []
    }
}

let str = "CGCGCGCGCG"

let ranges = str.findOccurencesOf(text: "CG")

print(ranges.count)   // 5

只需为textField Edit添加一个控件事件,并按以下方式遍历范围:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.addTarget(self, action: "coloring:", forControlEvents: UIControlEvents.EditingChanged)
        textField.becomeFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func coloring(sender:UITextField) {
        let attText = NSMutableAttributedString(string: sender.text ?? "")
        let ranges = sender.text!.uppercaseString.findOccurencesOf(text: "CG")
        for range in ranges {
            attText.addAttributes([NSForegroundColorAttributeName : UIColor.redColor()], range: range)
        }
        sender.attributedText = attText
    }

}

extension String {
    func findOccurencesOf(text text:String) -> [NSRange] {
        return !text.isEmpty ? try! NSRegularExpression(pattern: text, options: []).matchesInString(self, options: [], range: NSRange(0..<characters.count)).map{ $0.range } : []
    }
}