Java : Program to find a occurrence/count of a particular pattern in a given string


/*
* Find occurrence/count of a particular pattern in a given string .
* For example : you have to search for a pattern ca#e or ca$e or ca&e or ca1e
* where 3 character could be any thing but first 2 chars and last
* should contain the c ,a and e respectively.
*
* Input = "carehappyca#eforyouca$ecccaseeeeca@ca$e"
* output = 5
*
* Condition : You don't have to use any inbuilt function like split() or regex() function etc.
*
*/

public class CountPatternInStringSequence {


public int countPatternInStringSequence(String str){

char[] ch = str.toCharArray(); // convert the given string to character array;
int i = 0;
int count = 0;

while(i < ch.length){

if(ch[i] == 'c'){
i++;
if(ch[i] == 'a'){
i= i+2;
if(ch[i] == 'e'){
count++;
}else{
i = i-2;
}
}else{

i = i-1;
}
}

i = i +1;

}
return count;
}

public static void main(String[] args) {

CountPatternInStringSequence fs = new CountPatternInStringSequence();
String str = "carehappyca#eforyouca$ecccaseeeeca@ca$e";
int totalCount = fs.countPatternInStringSequence(str);
System.out.println("Given String : " + str);
System.out.println("Total occurence of particular pattern found : " + totalCount);

}

}

/*
output:

Given String : carehappyca#eforyouca$ecccaseeeeca@ca$e
Total occurence of particular pattern found : 5

*/

πŸ””Announcement : Visit the new website/blog πŸ””

πŸ””πŸ””πŸ”” Announcement :  Visit the new website/blog πŸ””πŸ””πŸ”” Dear readers, Thank you for reading my blog. If you could have used the little info...