Skip to content

Commit 5363595

Browse files
authored
KTLN-693: How to Reverse a Sentence in Kotlin (#656)
* Added unit tests * unit tests fixes
1 parent b6d22c1 commit 5363595

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.baeldung.reversesentence
2+
import org.junit.Assert.assertEquals
3+
import org.junit.Test
4+
5+
class ReverseSentenceUnitTest {
6+
@Test
7+
fun `reverse sentence using custom method`() {
8+
val sentence = "this is a sentence"
9+
val expected = "ecnetnes a si siht"
10+
assertEquals(expected, reverseSentence(sentence))
11+
}
12+
13+
@Test
14+
fun `reverse sentence using string reversed() method`() {
15+
val sentence = "this is a sentence"
16+
val expected = "ecnetnes a si siht"
17+
assertEquals(expected, sentence.reversed())
18+
}
19+
20+
@Test
21+
fun `reverse sentence using stringbuilder reverse() method`() {
22+
val sentence = "this is a sentence"
23+
val expected = "ecnetnes a si siht"
24+
assertEquals(expected, StringBuilder(sentence).reverse().toString())
25+
}
26+
27+
@Test
28+
fun `reverse sentence using recursion method`() {
29+
val sentence = "this is a sentence"
30+
val expected = "ecnetnes a si siht"
31+
assertEquals(expected, reverseSentenceRecursively(sentence))
32+
}
33+
34+
}
35+
fun reverseSentence(sentence: String): String {
36+
var reversedSentence = ""
37+
for (i in sentence.length - 1 downTo 0) {
38+
reversedSentence += sentence[i]
39+
}
40+
return reversedSentence
41+
}
42+
fun reverseSentenceRecursively(sentence: String): String {
43+
return if (sentence.isEmpty()) {
44+
""
45+
} else {
46+
reverseSentenceRecursively(sentence.substring(1)) + sentence[0]
47+
}
48+
}

0 commit comments

Comments
 (0)