Q:

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

0

Write a Scala program to calculate the sum of the numbers appear 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): 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

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