To check if a string is a palindrome or not, we need to compare the original string with its reversed form. If both strings are the same, the original string is a palindrome.
Here’s an example Kotlin code to check if a string is a palindrome:
fun isPalindrome(str: String): Boolean {
val reversedStr = str.reversed()
return str == reversedStr
}
In this code, the isPalindrome
function takes a String
parameter str
and returns true
if str
is a palindrome, and false
otherwise. The function first creates a new string reversedStr
that is the reverse of str
, using the reversed()
method. The function then compares str
with reversedStr
and returns true
if they are equal, and false
otherwise.
fun isPalindrome(str: String): Boolean {
val reversedStr = str.reversed()
return str == reversedStr
}
fun main() {
val str1 = "racecar"
val str2 = "hello"
println("$str1 is palindrome: ${isPalindrome(str1)}")
println("$str2 is palindrome: ${isPalindrome(str2)}")
}
In this code, we create two strings str1
and str2
, with the values “racecar” and “hello”, respectively. We then call the isPalindrome
function to check if each string is a palindrome, and print the results to the console. The output will be:
racecar is palindrome: true
hello is palindrome: false