Skip to content

Java StringBuilder Contains Example (StringBuffer)

Java StringBuilder contains example shows how to check if StringBuilder contains a specified character or String. This example also shows how to check the same in the StringBuffer object.

How to check if StringBuilder contains character or String specified (StringBuffer)?

Java String class provides contains method which checks if the specified character sequence is contained within the String.

This method returns a boolean depending upon whether the String contains a specified sequence.

Unlike the String class, StringBuilder and StringBuffer classes do not provide a contains method. However, the StringBuilder/StringBuffer class provides indexOf method.

The indexOf method returns the index of the first occurrence of the specified substring. If the substring is not found, it returns -1. In the below example, we are going to use the indexOf method of the StringBuilder class to build our own version of the contains method.

Output

As you can see from the output, the contains method returns true for the first two method calls and false for the third one as StringBuilder does not contain the “Five” text. The above code also works for StringBuffer as they have similar APIs.

Output

Please also note that this implementation does not support the regex pattern. However, we can do that using the Pattern and Matcher classes.

Please also visit Java String Tutorial with Examples to learn more about String handling in Java.

Checkout ArrayList contains example, String contains example, check if the array contains a value, or check if String contains number example to learn more.

This example is a part of the Java StringBuffer tutorial and Java StringBuilder tutorial.

References:
StringBuilder JavaDoc
StringBuffer JavaDoc

About the author

1 comments

Leave a Reply

Your email address will not be published.