w3resource

Scala Programming: Check whether a prefix string creates using the first specific characters in a given string appears somewhere else in the string

Scala Programming String Exercise-31 with Solution

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.

Sample Solution:

Scala Code:

object Scala_String {
  def test(str1: String, n_chr: Int): Boolean = {
    var len = str1.length();
    var pre_str = str1.substring(0, n_chr);
    for (i <- n_chr to len - 1) {
      if (n_chr + i <= len) {
        if (pre_str.equals(str1.substring(i, n_chr + i)))
          return true;
      }
    }
    return false;
  }
  def main(args: Array[String]): Unit = {
    var str1 = "MrsJemsMrsam";
    var n = 3;
    var prechr = str1.substring(0, n);
    println("The given string is: " + str1);
    println("The prefix string length is: " + n);
    println("Is '" + prechr + "' appear else where in the string? " + test(str1, n))
    str1 = "MrJemsam";
    n = 2;
    prechr = str1.substring(0, n);
    println("The given string is: " + str1);
    println("The prefix string length is: " + n);
    println("Is '" + prechr + "' appear else where in the string? " + test(str1, n))
  }
}

Sample Output:

The given string is: MrsJemsMrsam
The prefix string length is: 3
Is 'Mrs' appear else where in the string? true
The given string is: MrJemsam
The prefix string length is: 2
Is 'Mr' appear else where in the 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 whether a substring appears before a period(.) within a given string.
Next: Write a Scala program to check whether a given substring presents in the middle of another given string. Here middle means difference between the number of characters to the left and right of the given substring not more than 1.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.