Check if a String Ends with a Certain Pattern in Java

06 May 2023 Balmiki Mandal 0 Core Java

Check if a String Ends with a Certain Pattern in Java

In Java, it is possible to check if a string ends with a certain pattern. This is often used to validate the contents of a string against a certain template before accepting it as input or passing it on to another system.

The easiest way to check if a string ends with a certain pattern is to use the endsWith() method of the String class. This method takes a string as an argument and returns a boolean value indicating whether or not the string ends with the specified pattern.

For example, consider a string that stores the name of a file:

String filename = "my-file.txt";

We can check if filename ends with a .txt extension like this:

boolean isTxt = filename.endsWith(".txt");

This will return true, since the filename ends with “.txt”. We can use this same technique to check if a string ends with any other pattern as well.

It is also possible to check if a string ends with any number of characters using the endsWith() method in combination with the substring() method. This can be useful when dealing with variable-length strings, such as user-generated input.

For example, consider a string that stores an email address:

String email = "[email protected]";

We can check if the email address ends with a specific domain name like this:

boolean isExample = email.endsWith(email.substring(email.indexOf("@")+1));

This will return true, since the email address ends with “example.com”. We can use this same technique to check if a string ends with any other pattern as well.

In summary, it is possible to check if a string ends with a certain pattern using the endsWith() method of the String class in Java. This can be used to validate the contents of a string before accepting it as input or passing it on to another system.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.