Skip to main content

How to check if a string contains only alphabetic characters in Kotlin

How to check if a string contains only alphabetic characters in Kotlin.

Here is a detailed step-by-step tutorial on how to check if a string contains only alphabetic characters in Kotlin.

Step 1: Declare a function to check if a string contains only alphabetic characters.

fun isAlphabetic(str: String): Boolean {
// Code to check if the string contains only alphabetic characters
}

Step 2: Use regular expressions to check if a string contains only alphabetic characters. Kotlin provides a built-in matches function that can be used with regular expressions.

fun isAlphabetic(str: String): Boolean {
return str.matches(Regex("[a-zA-Z]+"))
}

In this example, the regular expression [a-zA-Z]+ matches one or more occurrences of lowercase and uppercase alphabetic characters.

Step 3: Test the function with different inputs to verify its correctness.

fun main() {
val str1 = "Hello"
val str2 = "123"

println(isAlphabetic(str1)) // Output: true
println(isAlphabetic(str2)) // Output: false
}

In this example, the isAlphabetic function is tested with two strings. The first string contains only alphabetic characters, so it should return true. The second string contains numeric characters, so it should return false.

Step 4: Handle empty strings or null values. If the input string is empty or null, you may want to consider how to handle it. One approach is to treat an empty or null string as not containing alphabetic characters.

fun isAlphabetic(str: String?): Boolean {
return str?.matches(Regex("[a-zA-Z]+")) ?: false
}

In this modified example, the input string is declared as nullable (String?). The matches function is only called if the string is not null. If the string is null, the function returns false. This allows you to handle empty or null strings gracefully.

Step 5: Use the function in your code as needed. You can use the isAlphabetic function to validate user input, perform data validation, or any other scenario where you need to check if a string contains only alphabetic characters.

fun main() {
val userInput = readLine() // Read user input from the console

if (isAlphabetic(userInput)) {
println("Input contains only alphabetic characters")
} else {
println("Input contains non-alphabetic characters")
}
}

In this example, the user input is read from the console using the readLine function. The isAlphabetic function is then used to check if the input contains only alphabetic characters, and an appropriate message is printed based on the result.

That's it! You now know how to check if a string contains only alphabetic characters in Kotlin.