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. In this article, we’ll explore two methods to achieve this: using the contains()
method and the indexOf()
method.
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.
Let’s see an example:
“`
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
“
contains()` method efficiently checks for the presence of substrings within a string.
As you can see, the
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.
Here’s an example:
“`
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
“
indexOf()` method, you can not only check for the presence of a substring but also retrieve its position within the original string.
By using the
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.