获取倒数第二个斜杠后的字母。

huangapple go评论75阅读模式
英文:

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(&quot;/&quot;);
        if (position &lt; 0)
            position = parts.length + position;
        return parts[position];
    }

    public static void main(String[] args) {
        String url = &quot;https://imgur.com/a/12345/all&quot;;
        String r = getNthCharacters(url, -2);
        System.out.println(r);
    }
}

Result:

12345

huangapple
  • 本文由 发表于 2020年10月16日 10:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64382309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定