w3resource

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


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

Go to:


PREV : 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.

Scala Code Editor :

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

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.