How to extract the beginning of a string (prefix) in Kotlin

1 Answer

0 votes
fun extractPrefix(str: String, lengthOfPrefix: Int): String {
    // Extract the prefix
    val prefix = str.take(lengthOfPrefix)
    return prefix
}

fun main() {
    val str = "Software Programmer"
    val lengthOfPrefix = 5 // Length of the prefix you want to extract

    val prefix = extractPrefix(str, lengthOfPrefix)

    println("Prefix: $prefix")
}


   
      
/*
run:

Prefix: Softw
  
*/

 



answered May 1, 2025 by avibootz
...