• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

SoftwareTestingo - Interview Questions, Tutorial & Test Cases Template Examples

  • Home
  • Test Case Examples
  • Interview Questions
  • Interview Questions Asked
  • Java
  • Java Program
  • Selenium
  • Selenium Programs
  • Manual Testing
  • Difference
  • Tools
  • SQL
  • Contact Us
  • Search
SoftwareTestingo » Java » Java Programs » Substring Matching In Java

Substring Matching In Java

Last Updated on: August 14, 2022 By Softwaretestingo Editorial Board

What We Are Learn On This Post

  • Substring Matching In Java

Find Substring Matching In Java: If you want to check if a String contains a certain sub-string, there are a couple of ways to do it in Java. Most of them are similar to what you’d find in other programming languages, but there is one approach that is unique to Java. This involves using the Pattern class, which we’ll cover later on in the article.

Substring Matching In Java

The Below Solutions prints the total number of occurrences of the substring throughout the String and also includes the cases where overlapping matches do exist Without using any predefined methods.

Post Type:Java Programs For Beginners
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Substring Matching In Java Solution 1:

package com.softwaretestingo.interviewprograms;
public class FindMatchingSubstringEx1 
{
	public static void main(String[] args) 
	{
		String str="abababababaabb";
		String sub = "bab";

		int n = str.length();
		int m = sub.length();

		// index=-1 in case of no match, otherwise >=0(first match position)
		int index=str.indexOf(sub), i=index+1, count=(index>=0)?1:0;
		//System.out.println(i+" "+index+" "+count);

		// i will traverse up to only (m-n) position
		while(index!=-1 && i<=(n-m))
		{   
			index=str.substring(i, n).indexOf(sub);
			count=(index>=0)?count+1:count;
			i=i+index+1;  
			//System.out.println(i+" "+index);
		}
		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

Output:

Original String: abababababaabb
Sub String: bab
Total Number Of Substring Appears: 4

Substring Matching In Java Solution 2:

Here is the advanced version to find substring in string java. By implementing the length() of java also we can find out how many times the token occurred in a user entered the string.

package com.softwaretestingo.interviewprograms;
import java.util.Scanner;
public class FindMatchingSubstringEx2 
{
	public static void main(String[] args) 
	{
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter a sentence please:");
		String str = scanner.nextLine();
		System.out.println("Enter a sentence please:");
		String sub=scanner.next();
		int atIndex = 0;
		int count = 0;

		while (atIndex != -1)
		{
			atIndex = str.indexOf(sub, atIndex);

			if(atIndex != -1)
			{
				count++;
				atIndex += sub.length();
			}
		}
		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

Output:

Enter a sentence please: hellohellohello
Enter a sentence please: hello
Original String: hellohellohello
Sub String: hello
Total Number Of Substring Appears: 3

Substring Matching In Java Solution 3:

You can also follow the below programs to find the Substring Matching In Java easily.

package com.softwaretestingo.interviewprograms;
public class FindMatchingSubstringEx3 
{
	public static void main(String[] args) 
	{
		String str = "helloslkhellodjladfjhello";
		String findStr = "hello";

		int count = 0, lastIndex = 0;
		while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) 
		{
			lastIndex += findStr.length() - 1;
			count++;
		}
		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+findStr);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

Output:

Original String: helloslkhellodjladfjhello
Sub String: hello
Total Number Of Substring Appears: 3

Substring Matching In Java Solution 4:

Find The Number of Times Substrings Appear In String By RegularExpression

  • Patterns of arbitrary length
  • Overlapping matches (such as counting “232” in “23232” or “aa” in “aaa”)
  • Regular expression meta-characters
package com.softwaretestingo.interviewprograms;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FindMatchingSubstringEx4 
{
	static int countMatches(Pattern pattern, String string)
	{
		Matcher matcher = pattern.matcher(string);

		int count = 0;
		int pos = 0;
		while (matcher.find(pos))
		{
			count++;
			pos = matcher.start() + 1;
		}

		return count;
	}
	public static void main(String[] args) 
	{
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter a sentence please:");
		String str = sc.nextLine();
		System.out.println("Enter a sentence please:");
		String sub=sc.next();
		Pattern pattern = Pattern.compile(sub);
		int count = countMatches(pattern, str);
		System.out.println("No Of Times Sub String Appears: "+count);
	}
}

Output:

Enter a sentence please: 23232
Enter a sentence please: 232
No Of Times Sub String Appears: 2

Java Find Substring Solution 5:

package com.softwaretestingo.interviewprograms;
import java.util.Scanner;
public class FindMatchingSubstringEx5 
{
	public static void main(String[] args) 
	{
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter a sentence please:");
		String str = scanner.nextLine();
		System.out.println("Enter a sentence please:");
		String sub=scanner.next();

		int lastIndex = 0;
		int count = 0;

		while((lastIndex = str.indexOf(sub, lastIndex)) != -1)
		{
			count++;
			lastIndex += sub.length() - 1;
		}
		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

Output:

Enter a sentence please: helloslkhellodjladfjhello
Enter a sentence please: hello
Original String: helloslkhellodjladfjhello
Sub String: hello
Total Number Of Substring Appears: 3

Java Match Substring Solution 6:

package com.softwaretestingo.interviewprograms;
import java.util.Scanner;
public class FindMatchingSubstringEx6 
{
	public  static  int getCountSubString(String str , String sub)
	{
		int n = 0, m = 0, counter = 0, counterSub = 0;
		while(n < str.length())
		{
			counter = 0;
			m = 0;
			while(m < sub.length() && str.charAt(n) == sub.charAt(m))
			{
				counter++;
				m++; n++;
			}
			if (counter == sub.length())
			{
				counterSub++;
				continue;
			}
			else if(counter > 0)
			{
				continue;
			}
			n++;
		}

		return  counterSub;
	}
	public static void main(String[] args) 
	{
		int count;
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a sentence please:");
		String str = scanner.nextLine();
		System.out.println("Enter a sentence please:");
		String sub=scanner.next();
		FindMatchingSubstringEx6 obj=new FindMatchingSubstringEx6();
		count=obj.getCountSubString(str, sub);

		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

Output:

Enter a sentence please: helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello
Enter a sentence please: hello
Original String: helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello
Sub String: hello
Total Number Of Substring Appears: 7

Find Substring In String Java Solution 7:

here is the other solution without using regexp/patterns/matches or even not using StringUtils.

package com.softwaretestingo.interviewprograms;
import java.util.Scanner;
public class FindMatchingSubstringEx7 
{
	public static void main(String[] args) 
	{

		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter a sentence please:");
		String str = scanner.nextLine();
		System.out.println("Enter a sentence please:");
		String sub=scanner.next();

		int count =0;
		int findStrLength = sub.length();
		for(int i=0;i<str.length();i++)
		{
			if(sub.startsWith(Character.toString(str.charAt(i))))
			{
				if(str.substring(i).length() >= findStrLength)
				{
					if(str.substring(i, i+findStrLength).equals(sub))
					{
						count++;
					}
				}
			}
		}

		System.out.println("Original String: "+str);
		System.out.println("Sub String: "+sub);
		System.out.println("Total Number Of Substring Appears: "+count);
	}
}

Output:

Enter a sentence please: helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello
Enter a sentence please: hello
Original String: helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello
Sub String: hello
Total Number Of Substring Appears: 7

Conclusion:

In this blog post, we have discussed in detail all the possible ways. In this blog post, we have shared 7 possible ways to find substring in string java. But let us know in the comment section if you are following any alternative way to find the matching substring.

    Filed Under: Java Programs

    Reader Interactions

    Leave a Reply Cancel reply

    Your email address will not be published. Required fields are marked *

    Primary Sidebar

    Join SoftwareTestingo Telegram Group

    Categories

    Copyright © 2023 SoftwareTestingo.com ~ Contact Us ~ Sitemap ~ Privacy Policy ~ Testing Careers