Converting String to integer in Scheme
Asked Answered
C

2

23

How can I convert a string of digits to an integer ? I want "365" to be converted to 365.

What I have tried, string->list then char->integer, but this returns ASCII value of that integer, how can I get that integer ?

Please help.

Clance answered 15/10, 2013 at 10:35 Comment(2)
(string->number "365")Lowerclassman
Possible duplicate hereOuphe
P
38

Try: string->number

> (string->number "1234")
1234
Plow answered 15/10, 2013 at 10:56 Comment(2)
ahha, i didn't try this. I was going by some long way, anyways ThanksClance
Related: #23027530Condensate
D
3

An alternative solution to parse integers from strings:

#lang typed/racket

(: numerical-char->integer (-> Char
                               Integer))
(define (numerical-char->integer char)
  (let ([num (- (char->integer char) 48)]) ; 48 = (char->integer #\0)
    (if
     (or (< num 0) (> num 9))
     (raise 'non-numerical-char #t)
     num)))

(: string->integer (-> String
                       Integer))
(define (string->integer str)
  (let ([char-list (string->list str)])
    (if (null? char-list)
        (raise 'empty-string #t)
        (foldl
         (λ([x : Integer] [y : Integer])
           (+ (* y 10) x))
         0
         (map numerical-char->integer char-list)))))
Doctrinal answered 1/4, 2017 at 10:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.