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

标签 swift nsrange

我希望 DNA 序列(字符串)中的所有 CG 字母对都显示为红色。我可以使用 NSMutableAttributedString 来完成。 为此,我需要所有 CG 位置的 NSRanges,并且我尝试在下面创建函数,但在

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

带范围的 rangeOfString 不能用类型的参数列表调用(字符串,选项:Int,范围: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
} 

最佳答案

正如 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 编辑添加一个控制事件,并按如下方式循环遍历范围:

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 } : []
    }
}

关于swift - 在 swift 中查找字符串中字符串的所有 NSRanges 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806108/

相关文章:

ios - UILabel 文字一一淡出

swift - 更改嵌套字典键的值

swift - xcode7 上出现错误。 view.layer.renderInContext(上下文!)

string - 获取 UITextView 中的当前段落?

ios - Textview scrollRangeToVisible 使范围到顶​​部

ios - RPScreenRecorder stopRecording block 未被调用

ios - tableViewCell 中的动画按钮

ios - 如何在 NSString 中查找 END_OF_LINE 或 WHITESPACE 字符

iphone - Objective-C 中的 NSRange 有问题吗?

objective-c - 从 NSRange 创建 UITextRange