Java: Get last element after split

后端 未结 12 1821
慢半拍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:10

    Save the array in a local variable and use the array's length field to find its length. Subtract one to account for it being 0-based:

    String[] bits = one.split("-");
    String lastOne = bits[bits.length-1];
    

    Caveat emptor: if the original string is composed of only the separator, for example "-" or "---", bits.length will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8

提交回复
热议问题