Uncovering the Power of Java Strings
When working with Java, understanding how to manipulate and analyze strings is crucial. One essential aspect of string manipulation is checking if a string contains a specific substring.
Method 1: Using the contains() Method
Imagine you have three strings: txt
, str1
, and str2
. You want to determine if str1
and str2
are present within txt
. The contains()
method comes to the rescue. This method returns a boolean value indicating whether the specified substring is present in the original string.
String txt = "Hello, world!";
String str1 = "world";
String str2 = "java";
System.out.println(txt.contains(str1)); // Output: true
System.out.println(txt.contains(str2)); // Output: false
As you can see, the contains()
method efficiently checks for the presence of substrings within a string.
Method 2: Using the indexOf() Method
Another approach to check if a string contains a substring is by using the indexOf()
method. This method returns the index of the first occurrence of the specified substring within the original string. If the substring is not found, it returns -1.
String txt = "Hello, world!";
String str1 = "world";
String str2 = "java";
System.out.println(txt.indexOf(str1)); // Output: 7
System.out.println(txt.indexOf(str2)); // Output: -1
By using the indexOf()
method, you can not only check for the presence of a substring but also retrieve its position within the original string.
Key Takeaways
In summary, both the contains()
and indexOf()
methods are essential tools for checking if a string contains a substring in Java. By mastering these methods, you’ll be able to write more efficient and effective code.
- The
contains()
method returns a boolean value indicating whether the specified substring is present in the original string. - The
indexOf()
method returns the index of the first occurrence of the specified substring within the original string, or -1 if not found.