Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to integer in Scheme

Tags:

scheme

racket

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.

like image 264
Hari Chaudhary Avatar asked Oct 15 '13 10:10

Hari Chaudhary


People also ask

How do I convert a string to a number?

The unary plus operator ( + ) will convert a string into a number. The operator will go before the operand. We can also use the unary plus operator ( + ) to convert a string into a floating point number. If the string value cannot be converted into a number then the result will be NaN .

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

Can we convert a string to int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed.


2 Answers

Try: string->number

> (string->number "1234")
1234
like image 135
DJG Avatar answered Oct 04 '22 06:10

DJG


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)))))
like image 42
test9753 Avatar answered Oct 04 '22 04:10

test9753