How to resolve the algorithm Count occurrences of a substring step by step in the Scala 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 Scala 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 Scala programming language

Source code in the scala programming language

import scala.annotation.tailrec
def countSubstring(str1:String, str2:String):Int={
   @tailrec def count(pos:Int, c:Int):Int={
      val idx=str1 indexOf(str2, pos)
      if(idx == -1) c else count(idx+str2.size, c+1)
   }
   count(0,0)
}


def countSubstring(str: String, sub: String): Int =
  str.sliding(sub.length).count(_ == sub)


def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length


println(countSubstring("ababababab", "abab"))
println(countSubstring("the three truths", "th"))


  

You may also check:How to resolve the algorithm Palindrome detection step by step in the C programming language
You may also check:How to resolve the algorithm Sum multiples of 3 and 5 step by step in the BCPL programming language
You may also check:How to resolve the algorithm Diversity prediction theorem step by step in the Perl programming language
You may also check:How to resolve the algorithm Doubly-linked list/Element insertion step by step in the Axe programming language
You may also check:How to resolve the algorithm Eertree step by step in the Racket programming language