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!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

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

🏆 All Time Leaderboard

Contest runs January 1, 1970 - December 31, 9999. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In