How to check if a string contains a substring 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
57,820 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
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
3,007 views
0 votes
0 answers

How to check whether a string contains a substring in JavaScript?

There doesn't seem to be a String.contains() ...READ MORE

Sep 21, 2022 in Java by Nicholas
• 7,760 points
616 views
0 votes
0 answers

How to check whether a string contains a substring in JavaScript?

Usually I would expect a String.contains() method, but there ...READ MORE

Sep 13, 2023 in Java by Rahul
• 240 points
505 views
0 votes
2 answers

What's the best way to check if a String represents an integer in Java?

You can also use regular expression. str.matches("-?\\d+"); It will ...READ MORE

answered Aug 9, 2018 in Java by Daisy
• 8,140 points
4,070 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,541 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,536 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,432 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,710 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
733 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,613 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