w3resource

Scala Programming: Check whether two strings of length 3 and 4 appear in same number of times in a given string

Scala Programming String Exercise-38 with Solution

Write a Java program to check whether two strings of length 3 and 4 appear in same number of times in a given string.

Sample Solution:

Scala Code:

object Scala_String {
  def test(stng: String, str1: String, str2: String): Boolean = {
  val l = stng.length;
  var red = 0;
  var blue = 0;
  for (i <- 0 to l-3) 
  {
    var tmp = stng.substring(i, i+3);
    if (tmp.compareTo(str2) == 0)
      red=red+1; 
     }
  for (i <- 0 to l-4) 
  {
    var tmp = stng.substring(i, i+4);
    if (tmp.compareTo(str1) == 0)
      blue=blue+1; 
  }
  
  if (red == blue)
    return true;
  else
    return false;
  }
  
  def main(args: Array[String]): Unit = {
      var strr =  "redcapmanwithbluecar";
      val str1 = "blue";  
      val str2 = "red";    
      println("The original string is: "+strr);
      println("Searched strings are: "+str1+","+str2);
      println("The appearance of red and blue are same: "+test(strr, str1, str2));
      strr =  "redcapmanwithbluecarblue";
      println("The original string is: "+strr);
      println("Searched strings are: "+str1+","+str2);
      println("The appearance of red and blue are same: "+test(strr, str1, str2));
    
 }
}

Sample Output:

The original string is: redcapmanwithbluecar
Searched strings are: blue,red
The appearance of red and blue are same: true
The original string is: redcapmanwithbluecarblue
Searched strings are: blue,red
The appearance of red and blue are same: false

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to create a new string from a given string after removing the 2nd character from the substring of length three starting with 'z' and ending with 'g' presents in the said string.
Next: Write a Scala program to create a new string repeating every character twice of a given string.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/string/scala-string-exercise-38.php