Skip to content

Instantly share code, notes, and snippets.

@LouisCAD
Created March 24, 2021 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LouisCAD/36f9f43099ff3d1f053bea9914684819 to your computer and use it in GitHub Desktop.
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.
/**
* 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