Remove extension from file name in Kotlin
This post will discuss how to remove extension from file name in Kotlin.
1. Using String.substring() function
A simple solution to extract the filename without extension using the substring() function. Its usage is demonstrated below, using the lastIndexOf() function to get the last index of the dot (.) in the filename.
|
1 2 3 4 5 |
fun main() { val fileName = "filename.txt" val fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.')) println(fileNameWithoutExtension) } |
The filename may have no extension. To handle this case, we should check the return value of the lastIndexOf() function before calling the substring() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun removeExtension(fileName: String): String { val lastIndex = fileName.lastIndexOf('.') if (lastIndex != -1) { return fileName.substring(0, lastIndex) } return fileName } fun main() { val fileName = "filename.txt" val fileNameWithoutExtension = removeExtension(fileName) println(fileNameWithoutExtension) } |
2. Using Regex
An alternative idea is to use the regular expression \.\w+$ which matches with the last dot and all the characters that follow it. The following solution uses the replaceAll() function that can accept a regular expression.
|
1 2 3 4 5 |
fun main() { val fileName = "filename.txt" val fileNameWithoutExtension = fileName.replace("\\.\\w+$".toRegex(), "") println(fileNameWithoutExtension) } |
That’s all about removing extension from file name in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)