在Java上使用String.endswith()方法
我有一个数组,我想检查最后的数字是否在数组中 例如:在Java上使用String.endswith()方法,java,Java,我有一个数组,我想检查最后的数字是否在数组中 例如: 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); 请注意: 我知道我可以使用for循环检查每个单独的项目 我想知道是否有更
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);
请注意:
我知道我可以使用for循环检查每个单独的项目
我想知道是否有更有效的方法。原因是图像字符串已在循环中不断更改。您可以将最后4个字符作为子字符串:
String ext=image.substring(image.length-4,image.length)代码>
然后使用HashMap
或其他一些搜索实现来查看它是否在您批准的文件扩展名列表中
如果(fileExtensionMap.containsKey(ext)){
使用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())));
您是否真的试图将布尔值命名为“true”?还是出于演示目的?@GearsdfGearsdfas true是Java保留的关键字。而且它不是一个很好的变量名,也不是很好的描述性名称。噢,LOL,我没有想到使用true,它刚刚发生了。@DavidB甚至比我的更简单。:)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())));