diff --git a/src/main/kotlin/strings/ReverseString.kt b/src/main/kotlin/strings/ReverseString.kt new file mode 100644 index 0000000..6de50ed --- /dev/null +++ b/src/main/kotlin/strings/ReverseString.kt @@ -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) +} diff --git a/src/test/kotlin/strings/ReverseStringTest.kt b/src/test/kotlin/strings/ReverseStringTest.kt new file mode 100644 index 0000000..944f102 --- /dev/null +++ b/src/test/kotlin/strings/ReverseStringTest.kt @@ -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)) + } +}