w3resource

Scala Programming: Test if a given string contains the specified sequence of char values

Scala Programming String Exercise-5 with Solution

Write a Scala program to test if a given string contains the specified sequence of char values.

Sample Solution:

Scala Code:

object Scala_String {  
  def test(str1: String, str2: String): Boolean = {
    str1.contains(str2)   
  }
  def main(args: Array[String]): Unit = {
        var str1 = "Scala Exercises and Python Exercises";
        var str2 = "and";
        println("Original String: " + str1);
        println("Specified sequence of char values: " + str2);
        println("Test if the said string contains the specified sequence of char values!")
        println(test(str1, str2))
        str1 = "Scala Exercises and PHP Exercises";
        str2 = "Python";
        println("Original String: " + str1);
        println("Specified sequence of char values: " + str2);
        println("Test if the said string contains the specified sequence of char values!")
        println(test(str1, str2))
      }
}

Sample Output:

Original String: Scala Exercises and Python Exercises
Specified sequence of char values: and
Test if the said string contains the specified sequence of char values!
true
Original String: Scala Exercises and PHP Exercises
Specified sequence of char values: Python
Test if the said string contains the specified sequence of char values!
false

Scala Code Editor :

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

Previous: Write a Scala program to concatenate a given string to the end of another string.
Next: Write a Scala program to create a new String object with the contents of a character array.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.