How to check if a string starts or ends with something
Short answer
Use startsWith() and endsWith():
void main() {
String file = "report.pdf";
IO.println(file.startsWith("rep"));
IO.println(file.endsWith(".pdf"));
}Output:
true
trueIgnoring case
These methods have no case-insensitive version, so lowercase the string first:
void main() {
String file = "PHOTO.JPG";
IO.println(file.toLowerCase(Locale.ROOT).endsWith(".jpg"));
}Output:
trueSeveral options
A stream makes it easy to check several endings at once:
void main() {
var images = List.of(".png", ".jpg", ".gif");
String file = "cat.gif";
IO.println(images.stream().anyMatch(file::endsWith));
}Output:
trueFrom a position
startsWith() accepts a second argument — the index to start checking from:
void main() {
IO.println("+7-900-123".startsWith("900", 3));
}Output:
trueCommon mistake
Checking a file extension with contains(). The string "pdf-viewer.exe" contains pdf, but it is not a PDF:
void main() {
String file = "pdf-viewer.exe";
IO.println(file.contains("pdf"));
IO.println(file.endsWith(".pdf"));
}Output:
true
falseFunctions used in this recipe
- String.startsWith() — Checks whether a string starts with the given prefix.
- String.endsWith() — Checks whether a string ends with the given suffix.
- String.toLowerCase() — Returns a copy of the string with all letters in lower case.