Get the last three chars from any string - Java

前端 未结 11 1468
情话喂你
情话喂你 2020-12-24 10:21

I\'m trying to take the last three chracters of any string and save it as another String variable. I\'m having some tough time with my thought process.

Strin         


        
11条回答
  •  执笔经年
    2020-12-24 10:56

    Here is a method I use to get the last xx of a string:

    public static String takeLast(String value, int count) {
        if (value == null || value.trim().length() == 0 || count < 1) {
            return "";
        }
    
        if (value.length() > count) {
            return value.substring(value.length() - count);
        } else {
            return value;
        }
    }
    

    Then use it like so:

    String testStr = "this is a test string";
    String last1 = takeLast(testStr, 1); //Output: g
    String last4 = takeLast(testStr, 4); //Output: ring
    

提交回复
热议问题