Contains Function in Java Example

The Java contains() method checks if a string contains another substring. The contains() method returns either True or False. Java contains() accepts one parameter: the substring to search for in your string.


Often, when you're working with strings, you'll want to determine whether a string contains a particular sequence of characters. For instance, this may come up if you are creating an app that checks whether a user's phone number contains a US-based country code.

Java offers a built-in method that is used to check whether a string contains a particular value: contains(). This tutorial will discuss, with reference to examples, how to use the String contains() method to check whether a string contains a substring in Java.

Java Strings

In Java, strings are used to store text-based data. Strings are sequences of zero or more characters that can include letters, symbols, whitespaces, and numbers.

Strings are declared as a sequence of characters surrounded by double quotes. Here's an example of a string in Java:

String phone_number = "+1 000 000 0000";

In this example, we have declared a variable called phone_number which stores a string value. Our string is assigned the value +1 000 000 0000.

Now that we know the basics of Java strings, we can discuss how to use the contains() method.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Java String contains()

The Java string data type offers a number of methods that can be used to process and manipulate the contents of a string. One of these methods is called contains(), which can be used to find out if a string contains a sequence of characters.

To clarify, contains() is a built-in Java method that checks whether a string contains a particular character or sequence of characters. Here's the syntax for the string contains() method:

string_name.contains(substring);

The contains() method accepts one parameter: the sequence of characters for which you want to search in your string.

contains() can return two possible values. If the string you have specified contains a substring, the contains() method returns true; otherwise, contains() returns false.

Suppose we are creating a program for a restaurant that checks for the reservation associated with a particular customer. Our program should accept the name of the customer and their booking number, and check whether the surname name the customer has given matches the one associated with their booking.

To check whether a customer's surname matches the one stored on-file, we could use this code:

form-submission

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses
class CheckReservation { 	public static void main(String[] args) { 		String name_on_file = "Jeff Clinton"; 		String name_given_to_clerk = "Clinton";  		if (name_on_file.contains(name_given_to_clerk)) { 			System.out.println("This reservation is confirmed."); 		} else { 			System.out.println("This reservation does not exist."); 		} 	} }          

When we run our code, the following response is returned:

This reservation is confirmed.

Let's break down our code. First, we declare a class called CheckReservation, which stores the code for our program. Then our program executes these steps:

  1. A variable called name_on_file is declared, which stores the full name our customer gave over the phone when making their reservation.
  2. name_given_to_clerk is declared, which is the surname of the customer.
  3. Our program uses the contains() method to check whether the name given when making the reservation matches the one given to the clerk.
    1. If the name on file includes the surname given to the clerk, This reservation is confirmed. is printed to the console.
    2. If the name on file does not include the surname given to the clerk, This reservation does not exist. is printed to the console.

The contains() method is useful if you want to check whether a string contains a particular substring. For instance, in the above example, we used the method to check whether our customer's full name contained the surname they had given our restaurant clerk.

Case Insensitive contains()

The Java contains() method is case sensitive. This means that even if the contents of the substring you have specified exist in a string, true will only be returned if the cases of those strings match.

However, there is a workaround you can use to check whether a string contains a particular substring, irrespective of cases. We can use the toLowerCase() or toUpperCase() methods to convert both the original string and the substring to lower or upper case so that when we use contains(), an equal comparison can be performed.

For instance, suppose our clerk had inserted the customer's surname in lowercase in our program. If this were to occur, our program would return:

This reservation does not exist.

Because the cases of the strings are different, our program would not recognize them as the same. However, if we used toLowerCase() or toUpperCase(), we could convert the cases of both strings to keep them consistent.

Let's return to the restaurant. Suppose we want all of our checks to be case-insensitive so that if our clerk uses the wrong case when checking for a reservation, the reservation does not automatically appear as non-existent. Here's an example of toUpperCase() being used to facilitate a case-insensitive check using the contains() method in Java:

class CheckReservation { 	public static void main(String[] args) { 		String name_on_file = "Jeff Clinton".toLowerCase(); 		String name_given_to_clerk = "clinton".toLowerCase();  		if (name_on_file.contains(name_given_to_clerk)) { 			System.out.println("This reservation is confirmed."); 		} else { 			System.out.println("This reservation does not exist."); 		} 	} }          

In this example, we have made a few changes. First, we have changed the case of the name given to the clerk to all-lowercase (the value is now clinton instead of Clinton). Second, we have used the toLowerCase() method to convert the variables name_on_file and name_given_to_clerk to lowercase.

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

Our code returns:

This reservation is confirmed.

Even though our "name_on_fil and name_given_to_clerk variables use different cases, the toLowerCase() method converts both variables to lowercase. So, an equal comparison can be performed.

The toUpperCase() method can be used in the same way as we used the toLowerCase() method above because it also facilitates an equal comparison between two strings.

If you're interested in learning more about the toUpperCase() and toLowerCase() methods, read about them in our tutorial on those methods here.

Conclusion

The string contains() method is used in Java to check whether a string contains a particular substring.

This tutorial discussed how to use the contains() method in Java, along with some examples to help you out. Additionally, we covered how to use the toUpperCase() and toLowerCase() methods to perform case-insensitive checks using contains().

Now you're ready to start using the Java string contains() method like an expert!

martyncatiche.blogspot.com

Source: https://careerkarma.com/blog/java-string-contains/

0 Response to "Contains Function in Java Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel