Always pick the last three characters without knowing the size of the string

Asked

Viewed 2,058 times

-1

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

String x = "OlaMundo"

Exit:

ndo

I can even do it using substring, the problem is I don’t know the size of the String, I don’t know what the word is.

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

  • String size is always determinable by the method length()

  • For tag you should read this: https://answall.com/q/101691/101. Your question is about Java and you did not have the tag. It wasn’t about Android Studio.

3 answers

2

The most basic form would be picking up the size:

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

The only problem is whether the string is less than 3, then you’d have to check it first. If you’re going to use it this way, it’s simpler than using a library. If you want to do the treatment I advise creating a function, so:

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);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • with this is possible I make a comparison with another String? output = and?

  • @Luccasbarrostavares Comparison of Strings in Java is always like the method equals and not ==

  • opa, I think I answered in rsrs haste, but Eae? how would I make the comparison? I’m trying to compare, but without success

1


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

String x = StringUtils.right("MinhaString", 3);

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 method .length() returns a number (integer type), you can do something of the type to compare before using:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.