Play Games

Search This Blog

Saturday, June 25, 2022

count number of times a character appears in a string in apex - Salesforce Globe For You

Solution: use countMatches(substring) to detrmine number of times a substring repeated in a string

Example: To determine number of times character 'e' repeated in 'salesforce globe for you'

String s = 'salesforce globe for you';

Integer numberoftimes = s.countMatches('e');

system.debug('Number of times :'+numberoftimes);

Output:

Note: CountMatches don't work if same character is in uppercase in one place and lowercase in other place.

Convert the string to lower or upper case first and then use the countMatches().

No comments:

Post a Comment