Reputation: 99
I have an array I want to check the 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);
Please note: I know I can check each individual item using a for loop.
I want to know if there is a more efficient way of doing this. Reason being is that image string is already on a loop on a constant change.
Upvotes: 5
Views: 5789
Reputation: 3116
Use Arrays.asList to convert to a List. Then you can check for membership.
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())));
Upvotes: 0
Reputation: 96385
Arrays.asList(types).contains(image.substring(image.lastIndexOf('.') + 1))
Upvotes: 14
Reputation: 2698
You can substring the last 4 characters:
String ext = image.substring(image.length - 4, image.length);
and then use a HashMap
or some other search implementation to see if it is in your list of approved file extensions.
if(fileExtensionMap.containsKey(ext)) {
Upvotes: 5