w3resource

Scala Programming: Check whether a substring appears before a period(.) within a given string

Scala Programming String Exercise-30 with Solution

Write a Scala program to check whether a substring appears before a period(.) within a given string.

Sample Solution:

Scala Code:

object Scala_String {
  def test(str1: String, str2: String): Boolean = {
    val len = str1.length
    var bool: Boolean = false;
    if (len < 3)
      return false;
    for (i <- 0 to len - 3) {
      var temp = str1.substring(i, i + 3);
      if (temp.compareTo(str2) == 0 && i == 0)
        bool = true;
      else if (temp.compareTo(str2) == 0 && str1.charAt(i - 1) != 46)
        bool = true;
    }
    return bool;
  }
  def main(args: Array[String]): Unit = {
    var str1 ="testabc.test";
    var str2 ="abc";
    println("The given string is: " + str1);
    println("Is "+ str2 + " appear before a period in the said string? " + test(str1, str2));    
    str1 ="test.abctest";
    str2 ="abc";
    println("The given string is: " + str1);
    println("Is "+ str2 + " appear before a period in the said string? " + test(str1, str2));
  }
}

Sample Output:

The given string is: testabc.test
Is abc appear before a period in the said string? true
The given string is: test.abctest
Is abc appear before a period in the said string? false

Scala Code Editor :

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

Previous: Write a Scala program to check two given strings whether any one of them appear at the end of the other string (ignore case sensitivity).
Next: Write a Scala program to check whether a prefix string creates using the first specific characters in a given string appears somewhere else in the string.

What is the difficulty level of this exercise?