The challenge
Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.
Example:
Given an input string of:
1
2
3
|
apples, pears # and bananas
grapes
bananas !apples
|
The output expected would be:
1
2
3
|
apples, pears
grapes
bananas
|
The code would be called like so:
1
2
|
var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", charArrayOf('#', '!'))
// result should == "apples, pears\ngrapes\nbananas"
|
The solution in Kotlin
Option 1:
1
2
3
4
|
fun solution(input: String, markers: CharArray): String =
input.lines().map { line ->
line.split(*markers).first().trimEnd()
}.joinToString("\n")
|
Option 2:
1
2
|
fun solution(input: String, markers: CharArray) =
input.lines().joinToString("\n") { it.takeWhile { !markers.contains(it) }.trim() }
|
Option 3:
1
2
3
4
5
6
7
|
fun solution(input: String, markers: CharArray): String {
return input.lines().map {
val parts = it.split(* markers);
if (parts.size > 1) parts.first().dropLast(1)
else parts.first();
}.joinToString("\n");
}
|
Test cases to validate our solution
1
2
3
4
5
6
7
8
9
10
|
import kotlin.test.assertEquals
import org.junit.Test
class TestExample {
@Test
fun testFixed() {
assertEquals("apples, plums\npears\noranges", solution("apples, plums % and bananas\npears\noranges !applesauce", charArrayOf('%', '!')))
assertEquals("Q\nu\ne", solution("Q @b\nu\ne -e f g", charArrayOf('@', '-')))
}
}
|