Get the last three chars from any string - Java

前端 未结 11 1424
情话喂你
情话喂你 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
    public String getLastThree(String myString) {
        if(myString.length() > 3)
            return myString.substring(myString.length()-3);
        else
            return myString;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 11:12

    The getChars string method does not return a value, instead it dumps its result into your buffer (or destination) array. The index parameter describes the start offset in your destination array.

    Try this link for a more verbose description of the getChars method.

    I agree with the others on this, I think substring would be a better way to handle what you're trying to accomplish.

    0 讨论(0)
  • 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!");
    }
    
    0 讨论(0)
  • 2020-12-24 11:16

    String newString = originalString.substring(originalString.length()-3);

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