Skip to content

Instantly share code, notes, and snippets.

@pyldin601
Created February 28, 2017 09:39
Show Gist options
  • Save pyldin601/4eb3711af842fed59eb01b58d9b02bcb to your computer and use it in GitHub Desktop.
Save pyldin601/4eb3711af842fed59eb01b58d9b02bcb to your computer and use it in GitHub Desktop.
String parser
enum class State { STRING, DIGIT }
fun stringToStructure(string: String): List<Pair<String, Int>> {
val result: MutableList<Pair<String, Int>> = mutableListOf()
var previousState = State.STRING
var stringAcc = ""
var numberAcc = ""
fun saveAccumulators() {
result.add(Pair(stringAcc, numberAcc.toInt()))
stringAcc = ""
numberAcc = ""
}
string.forEachIndexed { i, symbol ->
val newState = if (symbol.isLetter()) State.STRING else State.DIGIT
val isLastSymbol = i == string.lastIndex
if (newState == State.STRING && previousState == State.DIGIT) {
saveAccumulators()
}
when (newState) {
State.STRING -> stringAcc += symbol
State.DIGIT -> numberAcc += symbol
}
if (isLastSymbol) {
saveAccumulators()
}
previousState = newState
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment