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,260 points
56,756 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,460 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,870 points
66,619 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,710 points
3,232 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,770 points
1,265 views
0 votes
3 answers

How to check if a String is numeric in Java?

Check if a string is numeric public class ...READ MORE

answered Dec 29, 2020 in Java by Carlos
2,875 views
0 votes
2 answers

Store String inside a File using Java

We can use Apache Commons IO. It ...READ MORE

answered Jul 20, 2018 in Java by Sushmita
• 6,920 points
1,424 views
0 votes
3 answers

Adding text to a file using Java

try { final Path ...READ MORE

answered Sep 6, 2018 in Java by Sushmita
• 6,920 points
1,429 views
+1 vote
1 answer

Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

answered May 10, 2018 in Java by Rishabh
• 3,620 points
1,337 views
0 votes
1 answer

How to split Strings by space in Java ?

You can use split() method. str = "Hello ...READ MORE

answered May 16, 2018 in Java by sharth
• 3,370 points
1,597 views
0 votes
1 answer

How to Install Java in Windows system?

Hi@akhtar, You can follow the below-given steps to install ...READ MORE

answered Jul 7, 2020 in Java by MD
• 95,460 points
6,471 views
0 votes
1 answer

How to remove the last character from a string?

Hi@akhtar, You can use the StringBuffer class. It provides ...READ MORE

answered Dec 30, 2020 in Java by MD
• 95,460 points
668 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP