How do I check if a string contains a substring in Java

0 votes
Hi Team,

I have two Strings, str1 and str2. How do I check if str2 is contained within str1?
Dec 30, 2020 in Java by akhtar
• 38,240 points
54,228 views

1 answer to this question.

+2 votes

Hi@akhtar,

The first and foremost way to check for the presence of a substring is the .contains() method. It's provided by the String class itself and is very efficient. The method accepts a CharSequence and returns true if the sequence is present in the String we call the method on.

String string = "Java";
String substring = "va";
System.out.println(string.contains(substring));

Hope this helps!

Join Java Certification Program today and become certified expert.

Thanks!

answered Dec 30, 2020 by MD
• 95,440 points

edited Jul 5, 2023 by Khan Sarfaraz

Related Questions In Java

0 votes
4 answers

How do I check if a file exists in Java?

To test to see if a file ...READ MORE

answered Dec 29, 2020 in Java by Rajiv
• 8,910 points
62,870 views
0 votes
2 answers

How do I convert a String to an int in Java?

Use the lines of code mentioned below:- String ...READ MORE

answered Feb 9, 2022 in Java by Soham
• 9,700 points
2,848 views
0 votes
1 answer

How do I determine whether an array contains a particular value in Java?

Arrays.asList(yourArray).contains(yourValue) Warning: this doesn't work for arrays of ...READ MORE

answered Dec 21, 2020 in Java by Gitika
• 65,910 points
1,105 views