Write a Scala program to calculate the sum of the numbers appear in a given string

  • برمجة سكالا

Write a Scala program to calculate the sum of the numbers appear in a given string.

الأجوبة

object Scala_String {
  def test(stng: String): Int = {
  val l = stng.length;
  var sum = 0;
  var temp = "";
  for (i <- 0 to l-1) 
  {
    if (Character.isDigit(stng.charAt(i))) 
	{
      if (i < l-1 && Character.isDigit(stng.charAt(i+1))) 
	  {
        temp += stng.charAt(i);
      }
      else 
	  {
        temp += stng.charAt(i);
        sum += Integer.parseInt(temp);
        temp = "";
      }
    }
  }
  sum;
  }

  def main(args: Array[String]): Unit = {
      val str1 =  "it 15 is25 a 20string";
      println("The given string is: "+str1);
      println("The sum of the numbers in the said string is: "+test(str1));
  }
}

Sample Output:

The given string is: it 15 is25 a 20string
The sum of the numbers in the said string is: 60
هل كان المحتوى مفيد؟

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

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

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