Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added: ReverseString.kt #100

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/kotlin/strings/ReverseString.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package strings

/**
* Reverses a given string
*
* @param str The input string to be reversed.
* @return The reversed string.
*/
fun reverseString(str: String): String {
if (str.isNullOrEmpty()) {
return str
}

val charArray = str.toCharArray()
var i = 0
var j = str.length - 1

while (i < j) {
val temp = charArray[i]
charArray[i] = charArray[j]
charArray[j] = temp
i++
j--
}

return String(charArray)
}
35 changes: 35 additions & 0 deletions src/test/kotlin/strings/ReverseStringTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package strings

import org.junit.Assert.assertEquals
import org.junit.Test

class ReverseStringTest {

@Test
fun testReverseStringWithEmptyString() {
val input = ""
val expected = ""
assertEquals(expected, reverseString(input))
}

@Test
fun testReverseStringWithSingleCharacter() {
val input = "a"
val expected = "a"
assertEquals(expected, reverseString(input))
}

@Test
fun testReverseStringWithEvenLengthString() {
val input = "abcdef"
val expected = "fedcba"
assertEquals(expected, reverseString(input))
}

@Test
fun testReverseStringWithOddLengthString() {
val input = "hello"
val expected = "olleh"
assertEquals(expected, reverseString(input))
}
}