Contains function in java

Java String contains() method

contains() method is a String class method that will check whether the string contains the specified sequence of char values. In this post, we will learn about the contains() method.

  • Method declaration – public boolean contains(CharSequence s).
  • What does it do? – It accepts a sequence of characters in the function’s argument and checks whether that sequence of characters is present in the string or not.
  • What does it return? – It returns true or false based on whether the string contains the specified sequence of characters.

What is CharSequence? CharSequence is an interface in Java that represents a sequence of characters. This interface provides uniform, read-only access to many different kinds of char sequences. Below is the list of classes that implement this interface –

CharBuffer is an abstract class, and all others are normal classes. So, we can pass the objects of all of the normal classes into the contains() method arguments to check whether the string contains it or not.

Code Example
Does str contains string? true Does str contains stringBuilder? true Does str contains stringBuffer? true 
Internal implementation of the contains() method
public boolean contains(CharSequence s) < return indexOf(s.toString()) >= 0; >

As we can see that contains() method internally uses the indexOf() method to check whether it contains the character sequence or not.

The What If Scenarios

What if we pass an empty string into the function’s argument?

contains() method will always return true if we pass an empty string into the function’s argument.

What if we pass null into the function’s argument?

It will throw NullPointerException as shown below

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.toString()" because "s" is null

If you want to learn more about Strings and its methods, we recommend you read this article .

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].

Источник

Java String contains() Method

Find out if a string contains a sequence of characters:

String myStr = "Hello"; System.out.println(myStr.contains("Hel")); // true System.out.println(myStr.contains("e")); // true System.out.println(myStr.contains("Hi")); // false

Definition and Usage

The contains() method checks whether a string contains a sequence of characters.

Returns true if the characters exist and false if not.

Читайте также:  Событие onmouseover

Syntax

public boolean contains(CharSequence chars) 

Parameter Values

The CharSequence interface is a readable sequence of char values, found in the java.lang package.

Technical Details

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Метод contains() в Java

Метод contains() – это метод Java, позволяющий проверить, содержит ли String другую подстроку или нет. Возвращает логическое значение, поэтому его можно использовать непосредственно внутри операторов if.

Синтаксис строкового метода “Container”

public boolean String.contains(CharSequence s)

s – это последовательность поиска

Этот метод возвращает true, только если эта строка содержит «s», иначе false.

NullPointerException – если значение s является нулем.

public class Sample_String < public static void main(String[] args) < String str_Sample = "This is a String contains Example"; //Check if String contains a sequence System.out.println("Contains sequence 'ing': " + str_Sample.contains("ing")); System.out.println("Contains sequence 'Example': " + str_Sample.contains("Example")); //String contains method is case sensitive System.out.println("Contains sequence 'example': " + str_Sample.contains("example")); System.out.println("Contains sequence 'is String': " + str_Sample.contains("is String")); >>

Contains sequence ‘ing’: true
Contains sequence ‘Example’: true
Contains sequence ‘example’: false
Contains sequence ‘is String’: false

Когда использовать метод Contains() ?

Это обычный случай в программировании, когда вы хотите проверить, содержит ли конкретная строка определенную подстроку. Например, если вы хотите проверить, содержит ли строка “The big red fox” подстроку “red.”Этот метод полезен в такой ситуации.

public class IfExample < public static void main(String args[]) < String str1 = "Java string contains If else Example"; // In If-else statements you can use the contains() method if (str1.contains("example")) < System.out.println("The Keyword :example: is found in given string"); >else < System.out.println("The Keyword :example: is not found in the string"); >> >

The Keyword :example: is not found in the string

Источник

contains() in Java

Java Course - Mastering the Fundamentals

contains() method is a part of the Java String class. It searches for a sequence or set of characters in a given string (note that it can not be used for a single character, we shall discuss it more later). It has a boolean return type, i.e., true is returned if the string contains the sequence of characters else false .

Syntax of contains() in Java

contains() method belongs to the Java String class.

Syntax of this method is as follows:

Here, ch represents the sequence of characters to be searched. Hence, the contains method is called on the given string.

Parameters of contains() in Java

contains() method takes a single parameter. It is the sequence of characters that is to be searched. It can be a sequence of characters like string, StringBuffer, etc. Other datatypes like int shall result in an incompatible type error.

For example:

Here, ABC is the sequence of characters taken as the parameter.

Return Values of contains() in Java

Return Type: boolean

Since contains() is a boolean method. It returns —

  • true: If sequence of characters is present in the string
  • false: If the sequence of characters is not present in the string.
Читайте также:  Рамка вокруг таблицы

Exceptions of contains() in Java

The contains() method throws NullPointerException in case the value of the sequence of characters is null .

In the above program, NullPointerException occurs since we have passed null as a parameter for the method.

Example

Let’s consider a short example to see the use case of contains( ) method.

In the above Program, string str is declared. The method contains() has been used to check if the character sequences are a substring of str or not. If yes, true is returned, and false otherwise.

Note that for an empty string, true is returned since it is a subset of every string.

What is contains() method in Java?

Let’s discuss how the contains() method works internally and its signature.

The signature of contains () method is as follows:

From the signature, it is visible that it has a boolean return type. Let’s dive in and look at its internal implementation. (This is just for the sake of understanding, don’t worry much about the implementation)

Inside the method, first of all, the conversion of a sequence of characters to a string occurs. Further, the indexOf method is called. This method returns 0 or any higher number if it finds the string; otherwise, it returns -1. So once it is executed, the contains method returns true when the indexOf method returns 0 or any higher number; otherwise, it returns false.

More about the contains() method in Java

We have seen the use cases of contains() method. However, there are some limitations that need to be considered.

  • This method can not be used for searching a single character.
  • This method can not be used to find the index of the searched string in the given string.

More Examples of String.contains() in Java

Example 1: Java String contains()

Now that we have covered the basics of contains() let’s look at an example. Suppose you have a list of email addresses of the format «name»»age»@xyz.com. You need to check which email belongs to James. Here, contains() method can be called on the email addresses, let us see how:

(For the example we have just considered two emails, we can have a list of the same and using a loop contains method can be called on every element of the list i.e., every email address). So here we have called the contains() method on two strings representing two email addresses. One with the desired Name or string of characters (which returns true ). For the other string, the method returns false since no matching character sequence is found. Hence, we know which email address belongs to the particular user.

Example 2: Using contains() With if. else

We can use the method inside an if — else block as well. Let us look at the implementation. Consider a case where you need to perform some modifications or operations on the strings containing a particular sequence of characters. In this case, contains method with if-else block can be used. Let us see how

In the above program, we have checked if the string contains the desired sequence of characters or not, «World» in this case. Since here it does. Thus we have performed the desired string operation. Here, the concat method is used to append strings.

Читайте также:  Html style border solid font css

Example 3: Using case insensitive check

contains() method is case sensitive, however with some modifications we can use this method for case insensitive check.

Basically we can take help of toLowerCase() or toUpperCase() method. This way, both the string and sequence of characters are converted to lower case or upper case and can easily be checked. Below is the implementation.

In the above example, we have converted both the sequence and string to lowercase and uppercase for checking.

Example 4: Contains() with single character

In the above program, We used contains method for a single character ‘S’. However, this results in an error. Hence, contains method can not be used for a single character.

Conclusion

  • contains () method is a built-in Java method that helps us check if a sequence of characters is present inside a given string or not.
  • The return type of this method is boolean , thus returning true or false.
  • It takes a single parameter,i.e., the sequence of characters to be searched.
  • Major Application of this method includes verification tasks like checking if a string is a substring of the other.

Источник

Java String contains() Method: Check if String contains Substring

The Java String contains() method is used to check whether the specific set of characters are part of the given string or not. It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement.

Syntax of contains() method in Java

public boolean String.contains(CharSequence s)

s − This is the sequence to search in Java contains() method

Return Value

The contains() method in Java returns true only if this string contains “s” else false.

Java String contains() Method Example 1:

public class Sample_String < public static void main(String[] args) < String str_Sample = "This is a String contains Example"; //Check if String contains a sequence System.out.println("Contains sequence 'ing': " + str_Sample.contains("ing")); System.out.println("Contains sequence 'Example': " + str_Sample.contains("Example")); //String contains method is case sensitive System.out.println("Contains sequence 'example': " + str_Sample.contains("example")); System.out.println("Contains sequence 'is String': " + str_Sample.contains("is String")); >>

Expected Output:

Contains sequence 'ing': true Contains sequence 'Example': true Contains sequence 'example': false Contains sequence 'is String': false

When to use Contains() method?

contains() in Java is a common case in programming when you want to check if specific String contains a particular substring. For example, If you want to test if the String “The big red fox” contains the substring “red.” The string contains() in Java method is useful in such situation.

Java String contains() Method Example 2:
Java String contains() method in the if else Structure:

public class IfExample < public static void main(String args[]) < String str1 = "Java string contains If else Example"; // In If-else statements you can use the contains() method if (str1.contains("example")) < System.out.println("The Keyword :example: is found in given string"); >else < System.out.println("The Keyword :example: is not found in the string"); >> >

Expected Output:

The Keyword :example: is not found in the string class

Источник

Оцените статью