CharRange Example in Kotlin
You can define an CharRange object in Kotlin using ..
operator as shown in the following.
x..y
where x and y are character values.
Or, you can use CharRange constructor as shown in the following.
IntRange(x, y)
where x and y are character values.
The definition of CharRange constructor is as given below.
CharRange(start: Char, endInclusive: Char)
Create CharRange with start=’m’ and endInclusive=’s’
In the following program, we create a CharRange object using its constructor, with a start value of ‘m’, and endInclusive value of ‘s’.
Kotlin Program
fun main() {
val myRange = CharRange('m', 's')
for (ch in myRange) {
println(ch)
}
}
Output
m
n
o
p
q
r
s
Create CharRange with start=’m’ and endInclusive=’s’, using .. operator
As we have already mentioned, we can create an IntRange object using ..
operator. In the following program, we create an IntRange object with a range of [4, 9],
Kotlin Program
fun main() {
val myRange = 'm'..'s'
for (ch in myRange) {
println(ch)
}
}
Output
m
n
o
p
q
r
s
Check if element ‘r’ is in the given CharRange
In the following program, we check if the element ‘r’ is present in the CharRange(‘m’, ‘s’).
Kotlin Program
fun main() {
val myRange = 'm'..'s'
val element = 'r'
if (myRange.contains(element)) {
println("$element is present in the given CharRange.")
} else {
println("$element is not present in the given CharRange.")
}
}
Output
r is present in the given CharRange.