+ Start a Discussion
aam1raam1r 

How to count the number of occurrences of text within a string variable

Is there an easy way to count how many times some text or substring appears in an apex string variable?  So if a a varibale holds "The quick brown fox jumps over the lazy dog"  i want to find how many times fox appears in this string.
Best Answer chosen by aam1r
OFröhlichOFröhlich
this would be esasier (see string class definition):
countMatches(substring)
Returns the number of times the specified substring occurs in the current String.
Signature
public Integer countMatches(String substring)
Parameters
substring
Type: String
Return Value
Type: Integer

All Answers

aam1raam1r
Ok, i found a soution at https://www.rosettacode.org/wiki/Count_occurrences_of_a_substring#Apex and used the following to fit my purpose:
String substr = 'ABC';
String str = 'ABCZZZABCYABCABCXXABC';
Integer substrLen = substr.length();
Integer count = 0;
Integer index = str.indexOf(substr);
while (index >= 0) {
    count++;
    str = str.substring(index+substrLen);
    index = str.indexOf(substr);
}
Works a treat, where..
System.debug('Count String : '+count);
returns..
Count String : 5
Ajay K DubediAjay K Dubedi
Hi,

Please Use below code it works fine and counts the occurrence of words in the string:

Class----->
public class Count_String 
{
    public static void main()
    {
        String str = 'The quick brown fox jumps over the lazy dog';
        String str1 = str.toLowerCase();
        Map<String,Integer> Count_Map = New Map<String,Integer>();
        for(string st :str1.split(' '))
        {
            if(Count_Map.containskey(st))
            {
                Integer count = Count_Map.get(st);
                count ++;
                Count_Map.put(st,count);
            }
            else
            {
                Count_Map.put(st,1);
            }
        }
        for(String str2 : Count_Map.keyset())
        {
            System.debug(str2+ '---->' + Count_Map.get(str2));
        }
    }
}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
OFröhlichOFröhlich
this would be esasier (see string class definition):
countMatches(substring)
Returns the number of times the specified substring occurs in the current String.
Signature
public Integer countMatches(String substring)
Parameters
substring
Type: String
Return Value
Type: Integer
This was selected as the best answer
aam1raam1r
Thanks also Ajay for your comprehensive solution.  However, OFröhlich - now thats what i'm talking about.  Great answer. Many thanks!. 
Simple as..
String submission = 'The quick brown fox jumps over the lazy dog';
submission.countMatches('fox');  // returns the number of times 'fox' appears in the submission string variable

 
RAMPRASADH NATARAJANRAMPRASADH NATARAJAN
to count the number of Occurences of word in a string:

public class testCount2 {
   public static void counterMethod(String sentence){
       sentence = sentence.toLowerCase();
       List<String> wordList=sentence.split(' ');
       Set<String> wordSet=new Set<String>(wordList);
       Map<String,Integer> mapper=new Map<String,Integer>();
        
        for(String ws:wordSet){
            Integer count=0;
            for(String wl:wordList)
               if (ws==wl)
                   count+=1;
            mapper.put(ws, count);
        }
       Integer i=0;
       for(String ws:wordSet){
            System.debug(ws+' appears (' + mapper.get(ws) + ') times');  
            i+=1;
       }
   }
}