Q:

Write a Scala program to check whether the character immediately before and after a specified character is same in a given string

0

Write a Scala program to check whether the character immediately before and after a specified character is same in a given string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

object Scala_String {
  def test(stng: String, schar: Char): Boolean = {
    var l = stng.length;
    var found = true;
    var tmpString: Char = ' '
    for (i <- 0 to l - 1) {
      tmpString = stng(i)
      if (tmpString.compare(schar) == 0) {
        if (stng.charAt(i - 1) == stng.charAt(i + 1)) {
          found = true;
        } else {
          found = false;

        }
      }
    }
    found;
  }
  
  def main(args: Array[String]): Unit = {
    var str1 = "moon#night";
    var schar: Char = '#'
    println("The given string is: " + str1 + " and the specified character is: " + schar);
    println("The before and after " + schar + " both characters are same in the said string: " + test(str1,schar));
    str1 = " bat#$#ball"
    schar = '$'
    println("The given string is: " + str1 + " and the specified character is: " + schar);
    println("The before and after " + schar + " both characters are same in the said string: " + test(str1,schar))
    str1 = " bat#$ball"
    schar = '$'
    println("The given string is: " + str1 + " and the specified character is: " + schar);
    println("The before and after " + schar + " both characters are same in the said string: " + test(str1,schar))
  }
 }
Sample Output:
The given string is: moon#night and the specified character is: #
The before and after # both characters are same in the said string: true
The given string is:  bat#$#ball and the specified character is: $
The before and after $ both characters are same in the said string: true
The given string is:  bat#$ball and the specified character is: $
The before and after $ both characters are same in the said string: false

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now