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.
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.
Try: string->number
> (string->number "1234")
1234
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)))))
© 2022 - 2024 — McMap. All rights reserved.
(string->number "365")
– Lowerclassman