英文:
Getting the Letters After The Second To Last slash in a URL
问题
我有一个URL,我试图获取倒数第二个/
之后的字母。
尝试获取 12345
String url = "https://imgur.com/a/12345/all";
我在努力寻找如何为我的动态函数创建算法:
private static String getNthCharacters(String url, int position){
if(position == 1){
return url.substring(url.lastIndexOf("/") + 1);
}
return null;
}
Log.d(TAG, "onCreateView: " + getNthCharacters(url, 1));
有更好的方法吗?
英文:
I have a url that I'm trying to get the letters that are after the second to last /
Trying to get 12345
String url = "https://imgur.com/a/12345/all";
I am struggling to figure out how to create an algorithm for my dynamic function:
private static String getNthCharacters(String url, int position){
if(position == 1){
return url.substring(url.lastIndexOf("/") + 1);
}
return null;
}
Log.d(TAG, "onCreateView: " + getNthCharacters(url, 1));
Is there a better way to do this?
答案1
得分: 2
这将实现我认为你在询问的功能。它允许您通过向函数提供负位置来说“倒数第二”:
public class Test {
private static String getNthCharacters(String url, int position) {
String[] parts = url.split("/");
if (position < 0)
position = parts.length + position;
return parts[position];
}
public static void main(String[] args) {
String url = "https://imgur.com/a/12345/all";
String r = getNthCharacters(url, -2);
System.out.println(r);
}
}
结果:
12345
英文:
This will do what I think you're asking for. It lets you say "the second to last" by giving the function a negative position:
public class Test {
private static String getNthCharacters(String url, int position) {
String[] parts = url.split("/");
if (position < 0)
position = parts.length + position;
return parts[position];
}
public static void main(String[] args) {
String url = "https://imgur.com/a/12345/all";
String r = getNthCharacters(url, -2);
System.out.println(r);
}
}
Result:
12345
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论