Q:

Write a Scala program to check whether a specified character is happy or not. A character is happy when the same character appears to its left or right in a string

0

Write a Scala program to check whether a specified character is happy or not. A character is happy when the same character appears to its left or right in a 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, spc: Char): Boolean = {
    var l = stng.length();
    var char_happy = true;
    for (i <- 0 to l - 1) {
      if (stng.charAt(i) == spc) {
        if (i > 0 && stng.charAt(i - 1) == spc)
          char_happy = true;
        else if (i < l - 1 && stng.charAt(i + 1) == spc)
          char_happy = true;
        else
          char_happy = false;
      }
    }
    char_happy;
  }
  def main(args: Array[String]): Unit = {
    var str1 = "azzlea";
    var spc = 'z'
    println("The given string is: " + str1);
    println("Is " + spc + " happy in the said string: " + test(str1, spc));

    str1 = "abcfdkefg";
    spc = 'f'
    println("The given string is: " + str1);
    println("Is " + spc + " happy in the said string: " + test(str1, spc));
  }
}

Sample Output:

The given string is: azzlea
Is z happy in the said string: true
The given string is: abcfdkefg
Is f happy 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