Get the last three chars from any string - Java

前端 未结 11 1474
情话喂你
情话喂你 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条回答
  •  旧时难觅i
    2020-12-24 11:15

    Why not just String substr = word.substring(word.length() - 3)?

    Update

    Please make sure you check that the String is at least 3 characters long before calling substring():

    if (word.length() == 3) {
      return word;
    } else if (word.length() > 3) {
      return word.substring(word.length() - 3);
    } else {
      // whatever is appropriate in this case
      throw new IllegalArgumentException("word has less than 3 characters!");
    }
    

提交回复
热议问题