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
public String getLastThree(String myString) {
if(myString.length() > 3)
return myString.substring(myString.length()-3);
else
return myString;
}
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.
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.
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!");
}
String newString = originalString.substring(originalString.length()-3);