Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the line and column number of a character at some index in Text View?

I have a NSTextView in which I have lots of text.

How can I get the line and the column number of the character at some index?

Lets say, I have this text in the NSTextView:

"This is just a\ndummy text\nto show you\nwhat I mean."

And I need the line and column number for the 16th character. In this case:

Line: 2
Column: 2

How can I calculate/get this using Swift?

Another example:

"This is just a\ndummy text\nto show you\nwhat I mean."

And I want the line and row number for 15th (or 16th, if \n are counted too) character, like this:

Line: 2
Column: 1
like image 918
Dejan Skledar Avatar asked Apr 09 '15 20:04

Dejan Skledar


1 Answers

You just need to break your text lines using String method componentsSeparatedByString, then you just need to keep count of your lines, columns and character position as follow:

extension String {
    func characterRowAndLineAt(position: Int) -> (character: String, line: Int, column:Int)? {
        var lineNumber = 0
        var characterPosition = 0
        for line in components(separatedBy: .newlines) {
            lineNumber += 1
            var columnNumber = 0
            for column in line {
                characterPosition += 1
                columnNumber += 1
                if characterPosition == position {
                    return (String(column), lineNumber, columnNumber )
                }
            }
            characterPosition += 1
            if characterPosition == position {
                return ("\n", lineNumber, columnNumber+1 )
            }
        }
        return nil
    }
}

let myText    = "This is just a\ndummy text\nto show you\nwhat I mean."
let result    = myText.characterRowAndLineAt(position: 16) // "(.0 "d", .1 2, .2 1)"
let character = result?.character  // "d"
let line      = result?.line       // 2
let column    = result?.column     // 1
like image 57
Leo Dabus Avatar answered Sep 25 '22 08:09

Leo Dabus