我输入了一个字符串,它是一个URI
。如何获得最后一个路径段(在我的例子中是一个id)?
这是我的输入URL:
String uri = "http://base_path/some_segment/id"
并且我必须获得我尝试过的id:
String strId = "http://base_path/some_segment/id";
strId = strId.replace(path);
strId = strId.replaceAll("/", "");
Integer id = new Integer(strId);
return id.intValue();
但它不起作用,肯定有更好的方法来做到这一点。
发布于 2010-10-29 16:11:03
这就是你要找的吗:
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String path = uri.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
int id = Integer.parseInt(idStr);
另一个选择
URI uri = new URI("http://example.com/foo/bar/42?param=true");
String[] segments = uri.getPath().split("/");
String idStr = segments[segments.length-1];
int id = Integer.parseInt(idStr);
发布于 2015-02-19 20:30:02
import android.net.Uri;
Uri uri = Uri.parse("http://example.com/foo/bar/42?param=true");
String token = uri.getLastPathSegment();
发布于 2015-05-07 04:39:11
我知道这很陈旧,但这里的解决方案似乎相当冗长。如果您有URL
或URI
,只需要一个易于阅读的一行程序
String filename = new File(url.getPath()).getName();
或者如果你有一台String
String filename = new File(new URL(url).getPath()).getName();
https://stackoverflow.com/questions/4050087
复制相似问题