Find the Number of Occurrences of a Substring in a String - java
Why is the following algorithm not halting for me?
In the code below, str is the string I am searching in, and findStr is the string occurrences of which I'm trying to find.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr,lastIndex);
if( lastIndex != -1)
count++;
lastIndex += findStr.length();
}
System.out.println(count);
How about using StringUtils.countMatches from Apache Commons Lang?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
That outputs:
3
Your lastIndex += findStr.length(); was placed outside the brackets, causing an infinite loop (when no occurence was found, lastIndex was always to findStr.length()).
Here is the fixed version :
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(findStr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findStr.length();
}
}
System.out.println(count);
A shorter version. ;)
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(str.split(findStr, -1).length-1);
The last line was creating a problem. lastIndex would never be at -1, so there would be an infinite loop. This can be fixed by moving the last line of code into the if block.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){
lastIndex = str.indexOf(findStr,lastIndex);
if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
Do you really have to handle the matching yourself ? Especially if all you need is the number of occurences, regular expressions are tidier :
String str = "helloslkhellodjladfjhello";
Pattern p = Pattern.compile("hello");
Matcher m = p.matcher(str);
int count = 0;
while (m.find()){
count +=1;
}
System.out.println(count);
I'm very surprised no one has mentioned this one liner. It's simple, concise and performs slightly better than str.split(target, -1).length-1
public static int count(String str, String target) {
return (str.length() - str.replace(target, "").length()) / target.length();
}
Here it is, wrapped up in a nice and reusable method:
public static int count(String text, String find) {
int index = 0, count = 0, length = find.length();
while( (index = text.indexOf(find, index)) != -1 ) {
index += length; count++;
}
return count;
}
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int lastIndex = 0;
int count = 0;
while((lastIndex = str.indexOf(findStr, lastIndex)) != -1) {
count++;
lastIndex += findStr.length() - 1;
}
System.out.println(count);
at the end of the loop count is 3; hope it helps
public int countOfOccurrences(String str, String subStr) {
return (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length();
}
A lot of the given answers fail on one or more of:
Patterns of arbitrary length
Overlapping matches (such as counting "232" in "23232" or "aa" in "aaa")
Regular expression meta-characters
Here's what I wrote:
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;
}
Example call:
Pattern pattern = Pattern.compile("232");
int count = countMatches(pattern, "23232"); // Returns 2
If you want a non-regular-expression search, just compile your pattern appropriately with the LITERAL flag:
Pattern pattern = Pattern.compile("1+1", Pattern.LITERAL);
int count = countMatches(pattern, "1+1+1"); // Returns 2
You can number of occurrences using inbuilt library function:
import org.springframework.util.StringUtils;
StringUtils.countOccurrencesOf(result, "R-")
Increment lastIndex whenever you look for next occurrence.
Otherwise it's always finding the first substring (at position 0).
The answer given as correct is no good for counting things like line returns and is far too verbose. Later answers are better but all can be achieved simply with
str.split(findStr).length
It does not drop trailing matches using the example in the question.
public int indexOf(int ch,
int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
So your lastindex value is always 0 and it always finds hello in the string.
try adding lastIndex+=findStr.length() to the end of your loop, otherwise you will end up in an endless loop because once you found the substring, you are trying to find it again and again from the same last position.
Try this one. It replaces all the matches with a -.
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
int numberOfMatches = 0;
while (str.contains(findStr)){
str = str.replaceFirst(findStr, "-");
numberOfMatches++;
}
And if you don't want to destroy your str you can create a new string with the same content:
String str = "helloslkhellodjladfjhello";
String strDestroy = str;
String findStr = "hello";
int numberOfMatches = 0;
while (strDestroy.contains(findStr)){
strDestroy = strDestroy.replaceFirst(findStr, "-");
numberOfMatches++;
}
After executing this block these will be your values:
str = "helloslkhellodjladfjhello"
strDestroy = "-slk-djladfj-"
findStr = "hello"
numberOfMatches = 3
As #Mr_and_Mrs_D suggested:
String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;
Based on the existing answer(s) I'd like to add a "shorter" version without the if:
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(count); // output: 3
Here is the advanced version for counting how many times the token occurred in a user entered string:
public class StringIndexOf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence please: \n");
String string = scanner.nextLine();
int atIndex = 0;
int count = 0;
while (atIndex != -1)
{
atIndex = string.indexOf("hello", atIndex);
if(atIndex != -1)
{
count++;
atIndex += 5;
}
}
System.out.println(count);
}
}
This below method show how many time substring repeat on ur whole string. Hope use full to you:-
String searchPattern="aaa"; // search string
String str="aaaaaababaaaaaa"; // whole string
int searchLength = searchPattern.length();
int totalLength = str.length();
int k = 0;
for (int i = 0; i < totalLength - searchLength + 1; i++) {
String subStr = str.substring(i, searchLength + i);
if (subStr.equals(searchPattern)) {
k++;
}
}
This solution prints the total number of occurrence of a given substring throughout the string, also includes the cases where overlapping matches do exist.
class SubstringMatch{
public static void main(String []args){
//String str = "aaaaabaabdcaa";
//String sub = "aa";
//String str = "caaab";
//String sub = "aa";
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("count: "+count);
}
}
Matcher.results()
You can find the number of occurrences of a substring in a string using Java 9 method Matcher.results() with a single line of code.
It produces a Stream of MatchResult objects which correspond to captured substrings, and the only thing needed is to apply Stream.count() to obtain the number of elements in the stream.
public static long countOccurrences(String source, String find) {
return Pattern.compile(find) // Pattern
.matcher(source) // Mather
.results() // Stream<MatchResults>
.count();
}
main()
public static void main(String[] args) {
System.out.println(countOccurrences("helloslkhellodjladfjhello", "hello"));
}
Output:
3
here is the other solution without using regexp/patterns/matchers or even not using StringUtils.
String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
String findStr = "hello";
int count =0;
int findStrLength = findStr.length();
for(int i=0;i<str.length();i++){
if(findStr.startsWith(Character.toString(str.charAt(i)))){
if(str.substring(i).length() >= findStrLength){
if(str.substring(i, i+findStrLength).equals(findStr)){
count++;
}
}
}
}
System.out.println(count);
If you need the index of each substring within the original string, you can do something with indexOf like this:
private static List<Integer> getAllIndexesOfSubstringInString(String fullString, String substring) {
int pointIndex = 0;
List<Integer> allOccurences = new ArrayList<Integer>();
while(fullPdfText.indexOf(substring,pointIndex) >= 0){
allOccurences.add(fullPdfText.indexOf(substring, pointIndex));
pointIndex = fullPdfText.indexOf(substring, pointIndex) + substring.length();
}
return allOccurences;
}
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;
}
🍑 Just a little more peachy answer
public int countOccurrences(String str, String sub) {
if (str == null || str.length() == 0 || sub == null || sub.length() == 0) return 0;
int count = 0;
int i = 0;
while ((i = str.indexOf(sub, i)) != -1) {
count++;
i += sub.length();
}
return count;
}
I was asked this question in an interview just now and I went completely blank. (Like always, I told myself that the moment the interview ends ill get the solution) which I did, 5 mins after the call ended :(
int subCounter=0;
int count =0;
for(int i=0; i<str.length(); i++) {
if((subCounter==0 && "a".equals(str.substring(i,i+1)))
|| (subCounter==1 && "b".equals(str.substring(i,i+1)))
|| (subCounter==2 && "c".equals(str.substring(i,i+1)))) {
++subCounter;
}
if(subCounter==3) {
count = count+1;
subCounter=0;
}
}
System.out.println(count);
Related
How to use/modify Knuth-Morris-Pratt algorithm to convert any given string to palindrome
I have been given a task to create a class that given a String will create a palindrome with minimum number of assertions. Example Runs: Input: 123333 Output: 12333321 Input: 789 Output: 78987 Input: 1221 Output: 1221221 **Note a Palindrome should NOT return the same Palindrome. I tried using a modified KMP algorithm as stated here. I revert the string and compare it to the reverse + original string and then add the mismatches to the original string. However my function only works for inputs with trailing digits (first example input) however an input like 1234 will return 1234123, '92837465' will return '928374659283746' public static int[] computelps(String sample){ int[] lps = new int[sample.length()]; lps[0] = 0; int i = 1; int len = 0; // length of previous longest prefix suffix while (i < sample.length()) { if (sample.charAt(i) == sample.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } return lps; } public static void Solution(File samplefile) throws Exception { BufferedReader br = new BufferedReader(new FileReader(samplefile)); String firstline = br.readLine(); String line; while ((line = br.readLine()) != null) { String reverse_str = ""; String newline = line.replace(".", ""); for (int i = newline.length() - 1; i >= 0; i--) { reverse_str += newline.charAt(i); } int [] lps = computelps(reverse_str); // computes the lps of the pattern string String tot = reverse_str + newline; // KMP Algorithm modified. int x = 0; // index for total_string(tot) int y = 0; // index for pattern String palindrome = newline; while (x < tot.length()){ if(reverse_str.charAt(y) == tot.charAt(x)){ y++; x++; } if(y == reverse_str.length()) { y = lps[y - 1]; } else if( x < tot.length() && (reverse_str.charAt(y) != tot.charAt(x))){ palindrome += tot.charAt(x); if ( y!= 0){ y = lps[y-1]; } else{ x += 1; } } } System.out.println(palindrome); } } I would appreciate any help. I find algorithms very challenging so please bear with me if my approach or code is sub-par. *I fixed sample inputs and outputs as well as added my results.
It helps to split this problem in smaller problems, implement a separate method for each and check to see if each method works as expected. What will really help you will be to learn to use the debugger in your Ide. But until you do that you can test that each part of your code works as expected. So I simplified a little your code and split it up : public static void main(String[] args){ System.out.println("computelps " + ("[0, 0, 0, 0]".equals(Arrays.toString(computelps("4321"))) ? "works" : "doesn't work" )); System.out.println("reverse " + ("4321".equals(reverse("1234")) ? "works" : "doesn't work" )); System.out.println("Solution " + ("1234321".equals(Solution("1234")) ? "works" : "doesn't work" )); } public static int[] computelps(String sample){ int[] lps = new int[sample.length()]; lps[0] = 0; int i = 1; int len = 0; // length of previous longest prefix suffix while (i < sample.length()) { if (sample.charAt(i) == sample.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } return lps; } public static String Solution(String line) { String newline = line.replace(".", ""); String reverse_str = reverse(newline); int [] lps = computelps(reverse_str); // computes the lps of the pattern string // KMP Algorithm modified. return kpmModified(newline, reverse_str, lps); } private static String kpmModified(String newline, String reverse_str, int[] lps) { int x = 0; // index for total_string(tot) int y = 0; // index for pattern String tot = reverse_str + newline; String palindrome = newline; while (x < tot.length()){ if(reverse_str.charAt(y) == tot.charAt(x)){ y++; x++; } if(y == reverse_str.length()) { y = lps[y - 1]; } else if( x < tot.length() && (reverse_str.charAt(y) != tot.charAt(x))){ palindrome += tot.charAt(x); if ( y!= 0){ y = lps[y-1]; } else{ x += 1; } } } return palindrome; } private static String reverse(String newline) { String reverse_str = ""; for (int i = newline.length() - 1; i >= 0; i--) { reverse_str += newline.charAt(i); } return reverse_str; } And the result is computelps works reverse works Solution doesn't work So your bug is in kpmModified method. I can't spend more time and I'm not familiar with the algorithm but you should continue like this and figure our what part of that method has the bug.
I think you overthink the problem. The question is basically adding a string's reversed version back to it's original, but not every character, right? So you might need to find something like a pointer to tell the function where to start to reverse. One example. Let the string be 12333. If we add every character from the index string.length() to 0, it will be 1233333321, which is not correct, since there are duplicated 3's. We need to ignore those, so we need to add characters from string.length() - numOfDuplicateAtEnd to 0. public String palindromic(String num) { int i = num.length() - 1; while (i > -1 && num.charAt(i) == num.charAt(num.length() - 1)) i--; for (int k = i; k > -1; --k) num += num.substring(k, k + 1); return num; }
String message divide 10 character by character
I want to divide the following message by 10 character. I want to append every part into StringBuilder object. 04421,1,13,S,312|4000004130,1;4000000491,1;4000005240,1;4000005789,2;4000004978,2;4000004934,2;4000004936,1;4000000569,2;4000005400,1;4000000;4000004934,2; I have done the following solution : if(getMsgOtherPart(message) != null){ System.out.println("part message::"+getMsgOtherPart(message)); String newMessage = getMsgOtherPart(message) ; int len = newMessage.length(); System.out.println("len::"+len); int firstIndex = 0; int limit = 10; int lastIndex = 10; int count = 0; StringBuilder sb = new StringBuilder(); String completeMessage = null; for(int i = 0; i <= len;i++){ count++; if( count == limit && lastIndex < len){ sb.append(getSmsUniqueHeader()); sb.append(newMessage.substring(firstIndex,lastIndex)); sb.append("#"); sb.append("\n"); firstIndex = lastIndex; lastIndex = firstIndex + limit; count = 0; } else if(count < limit && i == len) { System.out.println("lastIndex:: "+lastIndex); sb.append(getSmsUniqueHeader()); sb.append(newMessage.substring(lastIndex-10)); sb.append("#"); } } completeMessage = sb.toString(); System.out.println("message::\n"+completeMessage); } I am getting output: message:: $04421,1,13# $,S,312|400# $0004130,1;# $4000000491# $;400000540# $0,1;400000# $0;40000000# $63,1;40000# $00076,1;40# $00000776,2# $;400000078# $8,2;400000# ------------ $0;# Please let me know to optimize my solution.
I had done this kind of thing in one of my project and here is the function i used, which return the List but you can modify it and use StringBuilder. public List<String> splitStringEqually(String txtStr, int subStringSize) { List<String> splittedStringList = new ArrayList<String>(); for (int start = 0; start < txtStr.length(); start += subStringSize) { splittedStringList.add(txtStr.substring(start, Math.min(txtStr.length(), start + subStringSize))); } return splittedStringList; }
You can use Google's Guava library and use the Splitter class for this. StringBuilder sb=new StringBuilder(); for(String s: Splitter.fixedLength(10).split(message)){ sb.append(s); sb.append("#\n"); } System.out.println(sb.toString());
String is maintained as char array internally. You can get the copy of that char array using message.toCharArray() and using a simple loop or java 8 streams pick elements in chunks of 10 and do whatever stuff you need to do.
Basing heavily on Rajen Raiyarela's answer and addressing the specific request from the OP, the code may look like this (upvote that one, not this one please!): public String splitStringEqually(String txtStr, int subStringSize) { // Start off with the header StringBuilder sb = new StringBuilder("message::\n"); int len = txtStr.length(); for (int start = 0; start < len; start += subStringSize) { sb.append("$"); // Copy the next 10 characters, or less if at end of string // Does not use txtStr.substring() as that creates an // unnecessary temporary string sb.append(txtStr, start, Math.min(len, start + subStringSize)); sb.append("#\n"); } return sb.toString(); } This can be called with simply: String completeMessage = splitStringEqually(newMessage, limit);
How to split string at every nth occurrence of character in Java
I would like to split a string at every 4th occurrence of a comma ,. How to do this? Below is an example: String str = "1,,,,,2,3,,1,,3,,"; Expected output: array[0]: 1,,,, array[1]: ,2,3,, array[2]: 1,,3,, I tried using Google Guava like this: Iterable<String> splitdata = Splitter.fixedLength(4).split(str); output: [1,,,, ,,2,, 3,,1, ,,3,, ,] I also tried this: String [] splitdata = str.split("(?<=\\G.{" + 4 + "})"); output: [1,,,, ,,2,, 3,,1, ,,3,, ,] Yet this is is not the output I want. I just want to split the string at every 4th occurrence of a comma. Thanks.
Take two int variable. One is to count the no of ','. If ',' occurs then the count will move. And if the count is go to 4 then reset it to 0. The other int value will indicate that from where the string will be cut off. it will start from 0 and after the first string will be detected the the end point (char position in string) will be the first point of the next. Use the this start point and current end point (i+1 because after the occurrence happen the i value will be incremented). Finally add the string in the array list. This is a sample code. Hope this will help you. Sorry for my bad English. String str = "1,,,,,2,3,,1,,3,,"; int k = 0; int startPoint = 0; ArrayList<String> arrayList = new ArrayList<>(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ',') { k++; if (k == 4) { String ab = str.substring(startPoint, i+1); System.out.println(ab); arrayList.add(ab); startPoint = i+1; k = 0; } } }
Here's a more flexible function, using an idea from this answer: static List<String> splitAtNthOccurrence(String input, int n, String delimiter) { List<String> pieces = new ArrayList<>(); // *? is the reluctant quantifier String regex = Strings.repeat(".*?" + delimiter, n); Matcher matcher = Pattern.compile(regex).matcher(input); int lastEndOfMatch = -1; while (matcher.find()) { pieces.add(matcher.group()); lastEndOfMatch = matcher.end(); } if (lastEndOfMatch != -1) { pieces.add(input.substring(lastEndOfMatch)); } return pieces; } This is how you call it using your example: String input = "1,,,,,2,3,,1,,3,,"; List<String> pieces = splitAtNthOccurrence(input, 4, ","); pieces.forEach(System.out::println); // Output: // 1,,,, // ,2,3,, // 1,,3,, I use Strings.repeat from Guava.
try this also, if you want result in array String str = "1,,,,,2,3,,1,,3,,"; System.out.println(str); char c[] = str.toCharArray(); int ptnCnt = 0; for (char d : c) { if(d==',') ptnCnt++; } String result[] = new String[ptnCnt/4]; int i=-1; int beginIndex = 0; int cnt=0,loopcount=0; for (char ele : c) { loopcount++; if(ele==',') cnt++; if(cnt==4){ cnt=0; result[++i]=str.substring(beginIndex,loopcount); beginIndex=loopcount; } } for (String string : result) { System.out.println(string); }
This work pefectly and tested in Java 8 public String[] split(String input,int at){ String[] out = new String[2]; String p = String.format("((?:[^/]*/){%s}[^/]*)/(.*)",at); Pattern pat = Pattern.compile(p); Matcher matcher = pat.matcher(input); if (matcher.matches()) { out[0] = matcher.group(1);// left out[1] = matcher.group(2);// right } return out; } //Ex: D:/folder1/folder2/folder3/file1.txt //if at = 2, group(1) = D:/folder1/folder2 and group(2) = folder3/file1.txt
The accepted solution above by Saqib Rezwan does not add the leftover string to the list, if it divides the string after every 4th comma and the length of the string is 9 then it will leave the 9th character, and return the wrong list. A complete solution would be : private static ArrayList<String> splitStringAtNthOccurrence(String str, int n) { int k = 0; int startPoint = 0; ArrayList<String> list = new ArrayList(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ',') { k++; if (k == n) { String ab = str.substring(startPoint, i + 1); list.add(ab); startPoint = i + 1; k = 0; } } // if there is no comma left and there are still some character in the string // add them to list else if (!str.substring(i).contains(",")) { list.add(str.substring(startPoint)); break; } } return list; } }
Detecting multiple instances of word with .contains
I am trying to count the number of instances a certain string occurs within another string. The input string that I am searching is not formatted in any fashion. I am currently doing the below but it is obvious that it only counts .contains once. What is the most efficient way to count instances multiple times. public String computeBestFitKey() { if(this.inputText == null) return null; String answer = null; int bestCount = 0, tempCount = 0; for(String s: logicTemplate.getLogicMap().keySet()) { String[] keyWords = this.logicTemplate.getKeyWords(s); for(String word: keyWords) { if(this.inputText.toLowerCase().contains(word.toLowerCase())) { System.out.println("word found: "+word.toLowerCase()); tempCount++; } } if(tempCount > bestCount) { bestCount = tempCount; answer = s; } tempCount = 0; } return answer; }
If you just need to count occurrences of a word, and it's not a homework assignment where you are restricted from using some of the standard facilities, then you can just do int numOccurrences = 0; Matcher m = Pattern.compile(word, Pattern.LITERAL).matcher(input); while (m.find()) numOccurrences++; Pattern.LITERAL is used to treat all character literally and ignore its special meaning in regex, if any.
You should be using indexOf(string str, int startFrom). Replace this line: if(this.inputText.toLowerCase().contains(word.toLowerCase())) { With these: int lastIndex = -1; String lowerTextInput = this.inputText.toLowerCase(); String lowerWord = word.toLowerCase(); while((lastIndex = (lowerTextInput .indexOf(lowerWord , lastIndex + 1)) > 0) What this does is that it assigns lastIndex the value of your substring. If the string does not contain the substring, it will yield -1 and thus the while condition will break. If it does exist, the value of lastIndex will be incremented by 1 and the search is made again. If you would like to make some improvements to this, especially if you are searching large strings, then I recommend you increase the value of lastIndex by the length of the substring you have matched.
static int countOccurences(String haystack, String needle) { int index, lastIndex = -1, count = 0; while ((index = haystack.indexOf(needle, lastIndex + 1)) != -1) { lastIndex = index; ++count; } return count; }
Creating a ubbi dubbi detector in java
I am trying to make an ubbi dubbi detector in java. I am currently trying to count how many ub's there are in the string and add them up to a counter and then if there is a certain number under the int I put, then it is not ubbi dubbi, but if it is equal to or above then it is ubbi dubbi. We aren't allowed to use regex, string builder, or arrays. Here is what I have currently: public static boolean detect(String phrase) { boolean isUbbi = false; int count = 0; CharSequence ub = "ub"; if (phrase.contains(ub)) { count++; } if (count >= 2) { isUbbi = true; } else { isUbbi = false; } return isUbbi; }
In your case it the condition never met to become true. Because if (phrase.contains(ub)) { count++; } And the condition is if (count >= 2) { // never met. Always false. That will check the occurrence once and then done.little more implementation is needed to check no of occurrences which involves a loop and sub-string etc.. If you are free to use Apache commons library use int count = StringUtils.countMatches(phrase, "ub"); If no libraries , String mainString = "ububsdfub"; Pattern pat = Pattern.compile("ub"); Matcher matcher = pat.matcher(mainString); int count = 0; while (matcher.find()) { count += 1; } System.out.println(count); // prints 3 since 3 ub's are there. With basic operation split(internally uses regex) String mainString = "ububsdfUb"; String occurance = "ub"; System.out.println(mainString.split(occurance, -1).length-1); Even split not allowed String mainString = "ububsdfub"; String occurance = "ub"; int index=0; int count=0; while ((index = mainString.indexOf(occurance, index)) != -1) { count++; index += occurance.length() - 1; } System.out.println(count);
You can count the number of occurrences by using String.indexOf(…). int count=0; for(int pos=phrase.indexOf(ub); pos>0; pos=phrase.indexOf(ub, pos)+1) count++; // now count contains the numbers of occurrences of ub in phrase
Here is what I came up with, just added the for loop and all works. public static boolean detect(String phrase) { boolean isUbbi = false; int count = 0; CharSequence ub = "ub"; for(int i = 0; i < phrase.length(); i++) { if (phrase.contains(ub)) { count++; } if (count >= 2) { isUbbi = true; } else { isUbbi = false; } } return isUbbi; }