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.
1 |
public boolean contains(CharSequence s) |
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.
1 |
public int indexOf(String str) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class JavaStringBuilderContainsExample { public static void main(String[] args) { //StringBuilder object StringBuilder sb = new StringBuilder("One Two Three"); System.out.println( contains(sb, "One") ); System.out.println( contains(sb, "Two") ); System.out.println( contains(sb, "Five") ); } public static boolean contains(StringBuilder sb, String findString){ /* * if the substring is found, position of the match is * returned which is >=0, if not -1 is returned */ return sb.indexOf(findString) > -1; } } |
Output
1 2 3 |
true true false |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public static void main(String[] args) { //StringBuffer object StringBuffer sb = new StringBuffer("Jan Feb March"); System.out.println( contains(sb, "Feb") ); System.out.println( contains(sb, "March") ); System.out.println( contains(sb, "July") ); } public static boolean contains(StringBuffer sb, String findString){ return sb.indexOf(findString) > -1; } |
Output
1 2 3 |
true true false |
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
Lovely