Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
true

Ignoring 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:

true

Several 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:

true

From a position

startsWith() accepts a second argument — the index to start checking from:

void main() {
    IO.println("+7-900-123".startsWith("900", 3));
}

Output:

true

Common 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
false

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.