Get the last three chars from any string - Java

前端 未结 11 1473
情话喂你
情话喂你 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 11:12

    If you want the String composed of the last three characters, you can use substring(int):

    String new_word = word.substring(word.length() - 3);
    

    If you actually want them as a character array, you should write

    char[] buffer = new char[3];
    int length = word.length();
    word.getChars(length - 3, length, buffer, 0);
    

    The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.

    If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.

提交回复
热议问题