I have a String say, val statement = "Ramu is a genius-boy, who likes tea."
Now, I convert this into list of words separated by space " " :
val ListOfString = ["Ramu", "is", "a", "genius-boy," "who", "likes", "tea."]
I want to know how do I copy "genius-boy", the number of times it contains "-"
so, final list should look like :
val listContainingConnectedWordCopies = ["Ramu", "is", "a", "genius-boy,", "genius-boy,", "who", "likes", "tea."]
even better would be this list
val listOfDisconnectedWords = ["Ramu", "is", "a", "genius,", "-boy,", "who", "likes", "tea."]
CodePudding user response:
The key here is to use flatMap
, to map one element of the list to multiple elements.
For listContainingConnectedWordCopies
, you can first count how many dashes there are, and generate a sequence containing one more copy than there are dashes. This is because when there are no dashes, you still want the word to appear in the resulting list once.
fun listContainingConnectedWordCopies(words: List<String>) =
words.flatMap { word ->
val dashCount = word.count { it == '-' }
generateSequence { word }.take(dashCount 1)
}
For listOfDisconnectedWords
, you can split each word by a regex that finds the index just before the dash, by using a lookahead. The result of this split is then used in a flatMap
:
fun listOfDisconnectedWords(words: List<String>) =
words.flatMap { it.split("(?=-)".toRegex()) }
Note that both of these solutions create new lists, rather than modify the existing list.