Skip to content

Instantly share code, notes, and snippets.

@zett42
Last active May 21, 2022 17:16
Show Gist options
  • Save zett42/ad026f229bb69e54adeba61a7ab7d5c3 to your computer and use it in GitHub Desktop.
Save zett42/ad026f229bb69e54adeba61a7ab7d5c3 to your computer and use it in GitHub Desktop.
Calculate line and column from character index
// Calculates line and column from character index.
(int, int ) CalcLineAndColumn( string text, int pos ) {
// Count the number of line breaks before pos.
int line = 0, lastLf = -1;
int lf = text.IndexOf( '\n' );
while( lf != -1 && lf < pos ) {
++line;
lastLf = lf;
lf = text.IndexOf( '\n', lf + 1 );
}
// Calculate number of chars since last line break before pos up to pos
int col = pos - lastLf - 1;
return (line, col);
}
//------------- TEST -------------
string text = @"AB
C
DE";
for( int i = 0; i < text.Length; ++i ) {
var (row, col) = CalcLineAndColumn( text, i );
Console.WriteLine( $"Pos: {i}, Row: {row}, Col: {col}, Char: #{(int)text[i]}" );
}
/* Output:
Pos: 0, Row: 0, Col: 0, Char: #65
Pos: 1, Row: 0, Col: 1, Char: #66
Pos: 2, Row: 0, Col: 2, Char: #13
Pos: 3, Row: 0, Col: 3, Char: #10
Pos: 4, Row: 1, Col: 0, Char: #67
Pos: 5, Row: 1, Col: 1, Char: #13
Pos: 6, Row: 1, Col: 2, Char: #10
Pos: 7, Row: 2, Col: 0, Char: #68
Pos: 8, Row: 2, Col: 1, Char: #69
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment