Write a Scala program to read a string and return the string without the first two characters. Keep the first char if it is 'g' and keep the second char if it is 'h'

  • برمجة سكالا

Write a Scala program to read a string and return the string without the first two characters. Keep the first char if it is 'g' and keep the second char if it is 'h'.

الأجوبة

object Scala_String {
  def test(str1: String): String = {
    var len = str1.length;
    var temp = "";
    for (i <- 0 to len - 1) {
      if (i == 0 && str1.charAt(i) == 'g')
        temp += 'g';
      else if (i == 1 && str1.charAt(i) == 'h')
        temp += 'h';
      else if (i > 1)
        temp += str1.charAt(i);
    }
    return temp;
  }
  def main(args: Array[String]): Unit = {
    var str1 = "ghost";
    println("The given strings is: " + str1);
    println("The new string is: " + test(str1))
    
    str1 = "photo";
    println("The given strings is: " + str1);
    println("The new string is: " + test(str1))
    str1 = "goat";
    
    println("The given strings is: " + str1);
    println("The new string is: " + test(str1))    
  }
}

Sample Output:

The given strings is: ghost
The new string is: ghost
The given strings is: photo
The new string is: hoto
The given strings is: goat
The new string is: gat
هل كان المحتوى مفيد؟

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

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

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