A string consist of digits and non-digit characters. The digits contains a series of positive integers. For instance, the string “abc22zit62de0f” contains the integers 22, 62 and 0.

Write a function to calculate the sum of the integers inside a string (es. 22 + 62 + 0 = 84)

## Sum of integers in a string

### Re: Sum of integers in a string

Hi cameo,

my first attempt would be:
if it needs to be faster I would do:

my first attempt would be:

Code: Select all

```
(define (parse-str str)
(apply + (map int (clean empty? (parse str {[^0-9]} 0)))))
```

Code: Select all

```
(define (parse-str str)
(let (total 0)
(dolist (s (parse str {[^0-9]} 0))
(unless (empty? s)
(inc total (int s))))
total))
```

### Re: Sum of integers in a string

Hi fdb,

thanks for your functions.

Only a problem: numbers with leading 0 will convert in octal base.
My function:
best regards,

cameyo

thanks for your functions.

Only a problem: numbers with leading 0 will convert in octal base.

Code: Select all

`Es. (parse-str "o123p010iru5") -> 136 (the correct value is 138)`

Code: Select all

```
(define (sum-str str)
(local (numeri expr)
(setq numeri '())
(setq expr {[0-9]+})
(replace expr str (push $0 numeri -1) 0)
(apply + (map (fn (x) (int x 0 10)) numeri))
))
(sum-str "o123p010iru5")
;-> 138
```

cameyo

### Re: Sum of integers in a string

In this case we could also do:

Code: Select all

```
> (apply + (map (fn (x) (int (if (starts-with x "0") (rest x) x))) (find-all {[0-9]+} "o123p010iru5")))
138
```

*Bertrand*−

**newLISP**v.10.7.6 64-bit

**on Linux**(

*Peppermint 9*)

### Re: Sum of integers in a string

Nice, I didn't know starts-with and didn't know I could use a regex in find-all, but then we could also simplify your code:

Code: Select all

```
> (apply + (map int (find-all {[1-9][0-9]*} "o123p010iru5")))
138
>
```

### Re: Sum of integers in a string

Or replacing the map with a function for apply, so only traversing the string two times

Code: Select all

```
> (apply (fn(x y) (+ (int x) (int y))) (find-all {[1-9]\d*} "o123p0010iru5") 2)
138
```

### Re: Sum of integers in a string

thank you. I learned new things.