Page **1** of **1**

### Sum of integers in a string

Posted: **Tue Jun 30, 2020 3:37 pm**

by **cameyo**

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)

### Re: Sum of integers in a string

Posted: **Wed Jul 01, 2020 3:23 am**

by **fdb**

Hi cameo,

my first attempt would be:

Code: Select all

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

if it needs to be faster I would do:

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

Posted: **Wed Jul 01, 2020 12:50 pm**

by **cameyo**

Hi fdb,

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)`

My function:

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
```

best regards,

cameyo

### Re: Sum of integers in a string

Posted: **Thu Jul 02, 2020 12:02 pm**

by **newBert**

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
```

### Re: Sum of integers in a string

Posted: **Thu Jul 02, 2020 4:27 pm**

by **fdb**

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

Posted: **Thu Jul 02, 2020 4:53 pm**

by **fdb**

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

Posted: **Fri Jul 03, 2020 10:26 am**

by **cameyo**

thank you. I learned new things.

### Re: Sum of integers in a string

Posted: **Fri Jul 03, 2020 1:22 pm**

by **newBert**

cameyo wrote: ↑Fri Jul 03, 2020 10:26 am

thank you. I learned new things.

You're welcome! I learned new things too... :)