You need to sign in to do that
Don't have an account?
aam1r
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.
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
Please Use below code it works fine and counts the occurrence of words in the string:
Class----->
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
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
Simple as..
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;
}
}
}