Count the number of times a substring occurs inside a given text. Overlapping matches must be counted. For example, the substring "aa" appears three times in "aaaa". Return 0 when either argument is null, when the substring is empty, or when the substring is longer than the text.

Examples:

Input: text = 'hello world', sub = 'l' Output: 3 Explanation: The character l appears at positions 2, 3, and 9 Input: text = 'aaaa', sub = 'aa' Output: 3 Explanation: Overlapping matches at positions 0, 1, and 2 Input: text = 'abc', sub = 'd' Output: 0 Explanation: The substring is not present in the text Input: text = 'abc', sub = '' Output: 0 Explanation: An empty substring returns zero by definition Input: text = null, sub = 'a' Output: 0 Explanation: Null text returns zero
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay July 2026

Contest runs July 1 - 31. Complete challenges to climb the leaderboard!

Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In