Write a Scala program to count how many times the substring 'life' present at anywhere in a given string. Counting can also happen for the substring 'li?e',any character instead of 'f'
object Scala_String {
def test(stng: String): Int = {
var l = stng.length();
var ctr = 0;
var firsttwo = "li";
val lastone = "e";
if (l < 4)
return 0;
for (i <- 0 to l - 3) {
if (firsttwo.compareTo(stng.substring(i, i + 2)) == 0 && lastone
.compareTo(stng.substring(i + 3, i + 4)) == 0)
ctr = ctr + 1;
}
return ctr;
}
def main(args: Array[String]): Unit = {
val str1 = "live on wild life";
println("The given string is: " + str1);
println("The substring life or li?e appear number of times: " + test(str1));
}
}
Sample Output:
The given string is: live on wild life
The substring life or li?e appear number of times: 2
Sample Output: