Created
February 28, 2017 09:39
-
-
Save pyldin601/4eb3711af842fed59eb01b58d9b02bcb to your computer and use it in GitHub Desktop.
String parser
This file contains hidden or 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
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