🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
contains method, indexOf method, matches method with regular expressions and Pattern and Matcher classes.Table of Contents
- Introduction
- Using
String.containsMethod - Using
String.indexOfMethod - Using
String.matchesMethod with Regular Expressions - Using
PatternandMatcherClasses - Conclusion
Introduction
Strings in Java are sequences of characters used to represent text. Checking if a string contains a specific substring can be done using various methods, each with its own advantages and use cases.
Using String.contains Method
The contains method checks if a string contains a specified sequence of characters.
Example
public class SubstringCheckExample {
public static void main(String[] args) {
String str = "Hello, world!";
String substr1 = "world";
String substr2 = "Java";
System.out.println(containsSubstring(str, substr1)); // true
System.out.println(containsSubstring(str, substr2)); // false
}
public static boolean containsSubstring(String str, String substr) {
return str.contains(substr);
}
}
Explanation
str.contains(substr): Returnstrueifstrcontainssubstr,falseotherwise.
Using String.indexOf Method
The indexOf method returns the index within the string of the first occurrence of the specified substring, or -1 if the substring is not found.
Example
public class SubstringCheckExample {
public static void main(String[] args) {
String str = "Hello, world!";
String substr1 = "world";
String substr2 = "Java";
System.out.println(containsSubstring(str, substr1)); // true
System.out.println(containsSubstring(str, substr2)); // false
}
public static boolean containsSubstring(String str, String substr) {
return str.indexOf(substr) != -1;
}
}
Explanation
str.indexOf(substr) != -1: Returnstrueifstrcontainssubstr,falseotherwise.
Using String.matches Method with Regular Expressions
The matches method can be used with regular expressions to check if a string contains a substring. However, this method is generally used for full string matching rather than partial matching.
Example
public class SubstringCheckExample {
public static void main(String[] args) {
String str = "Hello, world!";
String substr1 = "world";
String substr2 = "Java";
System.out.println(containsSubstring(str, substr1)); // true
System.out.println(containsSubstring(str, substr2)); // false
}
public static boolean containsSubstring(String str, String substr) {
return str.matches(".*" + substr + ".*");
}
}
Explanation
str.matches(".*" + substr + ".*"): Uses a regular expression to check ifstrcontainssubstr. The.*before and after the substring allows for any characters to be present before or after the substring.
Using Pattern and Matcher Classes
The Pattern and Matcher classes from the java.util.regex package provide more flexibility and control when working with regular expressions.
Example
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SubstringCheckExample {
public static void main(String[] args) {
String str = "Hello, world!";
String substr1 = "world";
String substr2 = "Java";
System.out.println(containsSubstring(str, substr1)); // true
System.out.println(containsSubstring(str, substr2)); // false
}
public static boolean containsSubstring(String str, String substr) {
Pattern pattern = Pattern.compile(Pattern.quote(substr));
Matcher matcher = pattern.matcher(str);
return matcher.find();
}
}
Explanation
Pattern.compile(Pattern.quote(substr)): Compiles the regular expression.Pattern.quoteis used to escape any special characters in the substring.matcher.find(): Returnstrueif the substring is found in the string,falseotherwise.
Conclusion
Checking if a string contains a substring in Java can be accomplished using various methods, including the contains method, indexOf method, matches method with regular expressions, and the Pattern and Matcher classes. Each method has its own advantages and specific use cases:
- The
containsmethod is straightforward and easy to use. - The
indexOfmethod is useful if you also need the index of the substring. - The
matchesmethod with regular expressions provides a way to use regex for substring checks, though it's more commonly used for full string matching. - The
PatternandMatcherclasses provide a flexible and powerful way to work with regular expressions, especially for complex patterns.
By understanding these methods, you can choose the most appropriate one for your specific use case when working with strings in Java.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment