I have a String paragraph that always gonna have 6 lines, like the example below.
val result= """
${getValue(A1)} ${getValue(A2)} ${getValue(A3)} ${getValue(A4)} ${getValue(A5)}
${getValue(B1)} ${getValue(B2)} ${getValue(B3)} ${getValue(B4)} ${getValue(B5)}
${getValue(C1)} ${getValue(C2)} ${getValue(C3)} ${getValue(C4)} ${getValue(C5)}
${getValue(D1)} ${getValue(D2)} ${getValue(D3)} ${getValue(D4)} ${getValue(D5)}
${getValue(E1)} ${getValue(E2)} ${getValue(E3)} ${getValue(E4)} ${getValue(E5)}
${getValue(F1)} ${getValue(F2)} ${getValue(F3)} ${getValue(F4)} ${getValue(F5)}
""".trimIndent()
getValue returns only one char, so the output is always something like this:
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
D D D D D
What I want is a way to remove specific lines from the past example by the line index.
For example I want an extention function that let me do this result.deleteLinesAt(3,5)
and it will output like this:
A A A A A
B B B B B
C C C C C
E E E E E
If this is not acheivable, can I find a way to remove the last N lines from a string paragraph
For example I want to type result.dropLastLines(2)
and it will output like this:
A A A A A
B B B B B
C C C C C
D D D D D
CodePudding user response:
val text = """
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
F F F F F
""".trimIndent()
fun String.deleteLinesAt(vararg lineNumbers: Int): String {
return this
.trim()
.split("\n")
.filterIndexed { index, _ -> index 1 !in lineNumbers }
.joinToString("\n")
}
val result = text.deleteLinesAt(3, 5)
And for dropping last lines:
val text = """
A A A A A
B B B B B
C C C C C
D D D D D
E E E E E
F F F F F
""".trimIndent()
fun String.dropLastLines(countOfLines: Int): String {
return this
.trim()
.split("\n")
.dropLast(countOfLines)
.joinToString("\n")
}
val result = text.dropLastLines(2)