To get the first N characters in a string in Kotlin, you can use the substring() method of the String class.
In this example,
str
with a string value.substring()
method of the string object str
to extract the first N characters.substring()
method takes two parameters: the starting index (inclusive) and the ending index (exclusive).fun main(args: Array<String>) {
val str = "Hello World";
val n = 5;
val firstN = str.substring(0, n);
print("First $n characters: $firstN");
}
First 5 characters: Hello
In this example,
str
with a string value.take()
function of the string object str
to extract the first N characters.take()
function takes the number of characters to take as its parameter.fun main(args: Array<String>) {
val str = "Hello World";
val n = 5;
val firstN = str.take(n);
print("First $n characters: $firstN");
}
First 5 characters: Hello
In this tutorial, we learned How to get First N Characters in String in Kotlin language with well detailed examples.