Java 如何将字符串拆分为android?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18787214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:03:00  来源:igfitidea点击:

How to split the string a android?

java

提问by Amrutha

I am working on android application. I am getting the image from gallery. Also I am getting the image path from gallery. Now my requirement is I want to get only the image name with the extension . How can I do that? Please help me.

我正在开发 android 应用程序。我正在从画廊获取图像。我也从画廊获取图像路径。现在我的要求是我只想获取带有扩展名的图像名称。我怎样才能做到这一点?请帮我。

String imgpath =  "/mnt/sdcard/joke.png";

The image extension can be anything joke.pngor joke.jpeg. I need to get the image name with extension finally.

图像扩展名可以是任何内容joke.pngjoke.jpeg. 我需要最终获得带有扩展名的图像名称。

i.e I want to split the above string and get only joke.png.

即我想拆分上面的字符串并只得到joke.png.

How can I achieve that? Please help me in this regard.

我怎样才能做到这一点?请在这方面帮助我。

采纳答案by Pankaj Kumar

String imgpath = "/mnt/sdcard/joke.png";

String result = imgpath.substring(imgpath.lastIndexOf("/") + 1); 
System.out.println("Image name " + result);

Output :-

输出 :-

Image name joke.png

You should read How do I get the file name from a String containing the Absolute file path?

您应该阅读如何从包含绝对文件路径的字符串中获取文件名?

回答by M.Sameer

You can do that in Android like in any Java program:

您可以像在任何 Java 程序中一样在 Android 中执行此操作:

String[] parts = imagepath.split("/");
String result = parts[parts.length-1];

回答by shivang Trivedi

String s[] = imgpath.split("/");
String result = s[s.length-1];

回答by ppeterka

You can get this with Regex too, if that is the hammer you have in your hands:

你也可以用正则表达式来得到这个,如果这是你手中的锤子:

String fileName = null;
Pattern pattern = Pattern.compile("(^|.*/)([^/]*)$");
Matcher m = pattern.getMatcher(filenameWithPath);
if(matcher.matches()) {

        fileName = matcher.group(2);
}

But don't be tempted to do this.This is less readable, and probably even slower than the other methods.

但不要试图这样做。这不太可读,甚至可能比其他方法慢。

回答by vish

String imgName = imgpath.substring((imgpath.lastIndexOf("/") + 1), imgpath.length());