24

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.

2
  • 4
    (string->number "365") Commented Oct 15, 2013 at 10:55
  • Possible duplicate here Commented Oct 15, 2013 at 14:48

2 Answers 2

40

Try: string->number

> (string->number "1234")
1234
Sign up to request clarification or add additional context in comments.

2 Comments

ahha, i didn't try this. I was going by some long way, anyways Thanks
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)))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.