Strip Comments in Kotlin

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:

apples, pears # and bananas grapes bananas !apples
Code language: PHP (php)

The output expected would be:

apples, pears grapes bananas

The code would be called like so:

var result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", charArrayOf('#', '!')) // result should == "apples, pears\ngrapes\nbananas"
Code language: JavaScript (javascript)

The solution in Kotlin

Option 1:

fun solution(input: String, markers: CharArray): String = input.lines().map { line -> line.split(*markers).first().trimEnd() }.joinToString("\n")
Code language: Kotlin (kotlin)

Option 2:

fun solution(input: String, markers: CharArray) = input.lines().joinToString("\n") { it.takeWhile { !markers.contains(it) }.trim() }
Code language: Kotlin (kotlin)

Option 3:

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"); }
Code language: Kotlin (kotlin)

Test cases to validate our solution

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('@', '-'))) } }
Code language: Kotlin (kotlin)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments