w3resource

Scala Programming: Calculate the sum of the numbers appear in a given string

Scala Programming String Exercise-45 with Solution

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

Sample Solution:

Scala Code:

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

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: 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.
Next: Write a Java program to check the number of appearances of the two substrings appear any where in the string.

What is the difficulty level of this exercise?