Get the last three chars from any string - Java

Java

Java Problem Overview


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.

String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);

I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?

Java Solutions


Solution 1 - Java

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 fewer than 3 characters!");
}

Solution 2 - Java

I would consider right method from StringUtils class from Apache Commons Lang: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)

It is safe. You will not get NullPointerException or StringIndexOutOfBoundsException.

Example usage:

StringUtils.right("abcdef", 3)

You can find more examples under the above link.

Solution 3 - Java

Here's some terse code that does the job using regex:

String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");

This code returns up to 3; if there are less than 3 it just returns the string.

This is how to do it safely without regex in one line:

String last3 = str == null || str.length() < 3 ? 
    str : str.substring(str.length() - 3);

By "safely", I mean without throwing an exception if the string is nulls or shorter than 3 characters (all the other answers are not "safe").


The above code is identical in effect to this code, if you prefer a more verbose, but potentially easier-to-read form:

String last3;
if (str == null || str.length() < 3) {
    last3 = str;
} else {
    last3 = str.substring(str.length() - 3);
}

Solution 4 - Java

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

Solution 5 - Java

public String getLastThree(String myString) {
    if(myString.length() > 3)
        return myString.substring(myString.length()-3);
    else
        return myString;
}

Solution 6 - Java

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.

Solution 7 - Java

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

Solution 8 - Java

This method would be helpful :

String rightPart(String text,int length)
{
    if (text.length()<length) return text;
    String raw = "";
    for (int i = 1; i <= length; i++) {
        raw += text.toCharArray()[text.length()-i];
    }
    return new StringBuilder(raw).reverse().toString();
}

Solution 9 - Java

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.

Solution 10 - Java

You can use a substring

String word = "onetwotwoone"
int lenght = word.length(); //Note this should be function.
String numbers = word.substring(word.length() - 3);

Solution 11 - Java

Alternative way for "insufficient string length or null" save:

String numbers = defaultValue();
try{
   numbers = word.substring(word.length() - 3);
} catch(Exception e) {
   System.out.println("Insufficient String length");
}

Solution 12 - Java

This method will return the x amount of characters from the end.

public static String lastXChars(String v, int x) {
    return v.length() <= x ? v : v.substring(v.length() - x);
}

//usage

System.out.println(lastXChars("stackoverflow", 4)); // flow

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEGHDKView Question on Stackoverflow
Solution 1 - JavaEgorView Answer on Stackoverflow
Solution 2 - JavaMichal PrzysuchaView Answer on Stackoverflow
Solution 3 - JavaBohemianView Answer on Stackoverflow
Solution 4 - JavaCratylusView Answer on Stackoverflow
Solution 5 - JavaChrisView Answer on Stackoverflow
Solution 6 - JavaMvGView Answer on Stackoverflow
Solution 7 - JavaPierreView Answer on Stackoverflow
Solution 8 - JavaMehdi AzadiView Answer on Stackoverflow
Solution 9 - JavacelestialorbView Answer on Stackoverflow
Solution 10 - JavaMatt BuscheView Answer on Stackoverflow
Solution 11 - JavaHodeifa BaswelView Answer on Stackoverflow
Solution 12 - JavamasterscodeView Answer on Stackoverflow