Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing specific lines from a string by index

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
D D D D D
""".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
D D D D D
""".trimIndent()

fun String.dropLastLines(countOfLines: Int): String {
  return this.trim().split("\n").dropLast(countOfLines).joinToString("\n")
}

val result = text.dropLastLines(2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading