Always get the last three characters without knowing the size of the String [closed]

0

I want to get the last three characters of a String . Example:

String x = "OlaMundo"

Output:

ndo

I can even do this using substring , the problem is that I do not know the size of String , I do not know what the word is.

Is there any way to do this without knowing the specific size of String ?

    
asked by anonymous 11.12.2018 / 22:21

3 answers

1

If you do not want to worry about doing string size validation, you can use the class StringUtils of package import org.apache.commons.lang3.StringUtils; ( library link ), would look like this:

String x = StringUtils.right("MinhaString", 3);
    
14.12.2018 / 11:57
2

The most basic way would be by taking the size:

x.substring(x.length() - 3);

The only problem is if the string is less than 3, then it would have to check first. If you use it that way is simpler than using a library. If you want to do the treatment I advise you to create a function, like this:

class Program {
    public static void main (String[] args) {
        System.out.println(Right("OlaMundo", 3));
    }

    public static String Right(String text, int length) {
        if (text.length() <= length) return null;
        return text.substring(text.length() - length);
    }
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

    
11.12.2018 / 22:28
0

You can get the size of it using

suaString.substring(suaString.length() - 3);

You will only have problems if your String is less than three characters long.

As the .length() method returns a number (integer type), you can do something of the type so you can compare before using:

if (suaString.length() >= 3) {
//Implanta o código
} else {
System.out.println("Sua String é menor que três caracteres!")
} 
    
14.12.2018 / 11:41