What's the most efficient way to trim the suffix in Java, like this:
title part1.txt title part2.html => title part1 title part2
Use Apache Commons IO, FilenameUtils. getBaseName(String filename) or removeExtension(String filename) , if you need the path too. Show activity on this post. Gracefully handles null , cases where there is nothing that looks like an extension and doesn't molest files that start with a . , this also handles the .
Using Regex\w+$ with the replaceAll() method that removes the last dot and all the characters that follow it. That's all about getting the filename without extension in Java.
GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.
The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff.
In this case, I recommend using FilenameUtils.removeExtension() from Apache Commons IO
str.substring(0, str.lastIndexOf('.'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With