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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With