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


i have nstextview in have lots of text.

how can line , column number of character @ index?

lets say, have text in nstextview:

"this a\ndummy text\nto show you\nwhat mean." 

and need line , column number 16th character. in case:

line: 2 column: 2 

how can calculate/get using swift?

another example:

"this a\ndummy text\nto show you\nwhat mean." 

and want line , row number 15th (or 16th, if \n counted too) character, this:

line: 2 column: 1 

you need break text lines using string method componentsseparatedbystring, need keep count of lines, columns , character position follow:

extension string {     func characterrowandlineat(#position: int) -> (character: string, line: int, column:int) {         var linenumber = 0         var characterposition = 0         line in componentsseparatedbystring("\n") {             linenumber++             var columnnumber = 0             column in line {                 characterposition++                 columnnumber++                 if characterposition == position {                     return (string(column), linenumber, columnnumber )                 }             }             characterposition++             if characterposition == position {                 return ("\n", linenumber, columnnumber+1 )             }         }         return ("", 0,0)     }   let mytext    = "this a\ndummy text\nto show you\nwhat 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 

Popular posts from this blog