Using the String.endswith () Method in Java

I have an array that I want to check the last digits if it is in the array.

Example:

String[] types = {".png",".jpg",".gif"}

String image = "beauty.jpg";
// Note that this is wrong. The parameter required is a string not an array.
Boolean true = image.endswith(types); 

Note: I know that I can check every single element using a for loop.

I want to know if there is a more efficient way to do this. The reason is that the image row is already in a loop with constant change.

+5
source share
3 answers
Arrays.asList(types).contains(image.substring(image.lastIndexOf('.') + 1))
+13
source

You can adjust the last 4 characters:

String ext = image.substring(image.length - 4, image.length);

and then use HashMapor some other search implementation to find out if it is on the list of approved file extensions.

if(fileExtensionMap.containsKey(ext)) {

+5
source

Arrays.asList . .

String[] types = {".png",".jpg",".gif"};
String image = "beauty.jpg";
if (image.contains(".")) 
    System.out.println(Arrays.asList(types).contains(
        image.substring(image.lastIndexOf('.'), image.length())));
0

All Articles