# Find Sum of Number in the String

• Find Sum of integers in the string "aa23sdsaadsfsd200sdfsf" .

Expected Answer 23+ 200 = 223

i Came up with the below code:

import math
import re

def getSum(str):
sum =0
i =0
arr1 = []
results = []
arr1 = re.findall(r'\d+', str1)
results = arr1
results = [int(i) for i in results]
print(arr1)
print(results)
print(listsum(results))

def listsum(numList):
theSum = 0
for i in numList:
theSum = theSum + i
return theSum

str1 = 'abc23dsdf200cde113ghjgv45364'
getSum(str1)

• This post is deleted!

• You can simplify if further:

``````import re

def getSum(str):
reduce(int.__add__, [int(each) for each in re.findall('\d+', str)])

getSum('abc23dsdf200cde113ghjgv45364')
``````

Java solution:

``````	public static int getSum(String str) {
int result = 0;

if (str == null || str.length() == 0)
return result;

StringBuilder sb = new StringBuilder();

for (char ch : str.toCharArray()) {
if (ch >= '0' && ch <= '9')
sb.append(Character.toString(ch));
else {
if (sb.length() > 0) {
result += Integer.parseInt(sb.toString());
sb = new StringBuilder();
}
}
}

char ch = str.charAt(str.length() - 1);

if (ch >= '0' && ch <= '9' && sb.length() > 0)
result += Integer.parseInt(sb.toString());

return result;
}
``````

• Here is my simple C# code:
public class Solution {
public int GetSumFromString(string s) {

``````	int i = s.Length-1;
int sum = 0;
int count = 0;

while(i>=0)
{
if(Char.IsDigit(s[i]))
{
sum += (int)Math.Pow(10,count)*(int)Char.GetNumericValue(s[i]);
count++;
}
else
count=0;
i--;
}
return sum;
}
``````

}

• ``````public int getSumofDigits(String s){

int i = 0;
int j = 0 ;
int len = ss.length() ;
int currentNum = 0;
int sum = 0 ;

while(i<len){
if(Character.isDigit(ss.charAt(i))){
j=i;
currentNum = 0 ;
while( j< len && Character.isDigit(ss.charAt(j))){
currentNum = currentNum *10 + ss.charAt(j) -48 ;
j++;
i++;
}

sum = sum + currentNum ;

}
i++ ;
}
return sum ;
}

``````

• '''
static void Main(string[] args)
{
Console.WriteLine("Enter the string");
string tmp = "";
int sum = 0,a=0;
foreach(char c in s)
{
if (c >= '0' && c <= '9')
{
tmp = tmp + c;
a = Convert.ToInt32(tmp);
}
else
{
sum = sum + a;
tmp = "";
a = 0;
}
}
Console.Write(sum);

• ``````  def sum_nums_in_string(s):

return sum(list(int(x) for x in re.findall('[\d]+', s)))
``````

This works just fine in Python...

• ``` import re def sum_from_string(string): return sum(map(int, re.findall(r'\d+', string)))```

``` ```

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.