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

  • برمجة سكالا

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.

الأجوبة

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
هل كان المحتوى مفيد؟

معلومات ذات صلة

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...