Java: Get last element after split

后端 未结 12 1797
慢半拍i
慢半拍i 2020-12-02 11:31

I am using the String split method and I want to have the last element. The size of the Array can change.

Example:

String one = \"Dü         


        
相关标签:
12条回答
  • 2020-12-02 12:26

    Also you can use java.util.ArrayDeque

    String last = new ArrayDeque<>(Arrays.asList("1-2".split("-"))).getLast();
    
    0 讨论(0)
  • 2020-12-02 12:28

    using a simple, yet generic, helper method like this:

    public static <T> T last(T[] array) {
        return array[array.length - 1];
    }
    

    you can rewrite:

    lastone = one.split("-")[..];
    

    as:

    lastone = last(one.split("-"));
    
    0 讨论(0)
  • 2020-12-02 12:29

    Or you could use lastIndexOf() method on String

    String last = string.substring(string.lastIndexOf('-') + 1);
    
    0 讨论(0)
  • 2020-12-02 12:29

    I guess you want to do this in i line. It is possible (a bit of juggling though =^)

    new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()
    

    tadaa, one line -> the result you want (if you split on " - " (space minus space) instead of only "-" (minus) you will loose the annoying space before the partition too =^) so "Günnewig Uebachs" instead of " Günnewig Uebachs" (with a space as first character)

    Nice extra -> no need for extra JAR files in the lib folder so you can keep your application light weight.

    0 讨论(0)
  • 2020-12-02 12:30

    You mean you don't know the sizes of the arrays at compile-time? At run-time they could be found by the value of lastone.length and lastwo.length .

    0 讨论(0)
  • 2020-12-02 12:33
    String str = "www.anywebsite.com/folder/subfolder/directory";
    int index = str.lastIndexOf('/');
    String lastString = str.substring(index +1);
    

    Now lastString has the value "directory"

    0 讨论(0)
提交回复
热议问题