Pattern search in a string in java

0

 


In this blog we will see how to write a program in which we are given a string and we have to find out whether the string contains the pattern or not.


public class PatternNaive {
public static void main(String args[])
{
String str="aaaaa";
String pat="aaa";
for(int i=0;i<str.length();i++)
{
if(pat.charAt(0)==str.charAt(i))
{
int count=1;
int k=1;
while(k<pat.length() && (i+k)<str.length())
{
if(pat.charAt(k)==str.charAt(i+k))
count++;
else
break;
k++;
}
if(count==pat.length())
System.out.println(i);
}
}

}
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !