Created
March 24, 2021 22:25
-
-
Save LouisCAD/36f9f43099ff3d1f053bea9914684819 to your computer and use it in GitHub Desktop.
Get the line and the column of an index in a given CharSequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns the line and the column of [index] in the given CharSequence. | |
*/ | |
fun CharSequence.getLineAndColumn(index: Int): LocationInText { | |
if (index !in 0..lastIndex) { | |
throw IndexOutOfBoundsException(index) | |
} | |
var lineNumber = 1 | |
var columnNumber = 1 | |
forEachIndexed { currentIndex, c -> | |
if (index == currentIndex) { | |
return LocationInText( | |
lineNumber = lineNumber, | |
columnNumber = columnNumber | |
) | |
} | |
when (c) { | |
'\n' -> { | |
lineNumber++ | |
columnNumber = 1 | |
} | |
else -> columnNumber++ | |
} | |
} | |
throw ConcurrentModificationException("The CharSequence has been shrunk concurrently") | |
} | |
data class LocationInText( | |
val lineNumber: Int, | |
val columnNumber: Int | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment