How to resolve the algorithm Count occurrences of a substring step by step in the Apex programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Count occurrences of a substring step by step in the Apex programming language

Table of Contents

Problem Statement

Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:

It should return an integer count. The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left   (see proof on talk page).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Count occurrences of a substring step by step in the Apex programming language

Source code in the apex programming language

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);
}
System.debug('Count String : '+count);

  

You may also check:How to resolve the algorithm IBAN step by step in the Fortran programming language
You may also check:How to resolve the algorithm Huffman coding step by step in the 11l programming language
You may also check:How to resolve the algorithm User input/Text step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm URL encoding step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Kronecker product step by step in the Simula programming language