user17227456
user17227456

Reputation: 1317

Nim have to convert string to int the simplest

How have Nim to convert string to int the simplest native way without a coder put import std... so on ?

var
 s = "99"
 si :int
 i = 1

si = s ...  # <- ? picturing 
i += si      # <-   - " -   must finely be 100

Upvotes: 3

Views: 2912

Answers (3)

Zectbumo
Zectbumo

Reputation: 4471

https://play.nim-lang.org/#ix=3Xlq

proc toInt(s: string): int =
  for c in s:
    result = result * 10 + c.int - '0'.int

Upvotes: 0

Grzegorz Adam Hankiewicz
Grzegorz Adam Hankiewicz

Reputation: 7661

Well, the only things you are requiring are that there are no imports used and that this is conversion is the simplest possible with the final result being 100, right? Essentially you don't care about:

  • should your conversion handle negative numbers?
  • should your conversion handle overflow, and how (return value/exception/other)?
  • should your conversion ignore invalid input silently?
  • should your conversion allow different inputs (non 99)?
  • should your conversion stop parsing at the first number or continue to extract all possible numbers?

This should fit the bill:

var
 s = "99"
 si :int
 i = 1

proc simplest_string_to_int(input: string): int = 99

si = simplest_string_to_int(s)
i += si      # <-   - " -   must finely be 100

echo i

Or alternatively, go look at the implementation of string parsing you don't want to import and copy&paste that into your code, so you don't have to import it.

Upvotes: 0

ftherien
ftherien

Reputation: 173

import std/strutils

var
  s = "99"
  i = 0
  s_int = parseInt(s)

i += s_int

I'm not sure why you don't want to import a standard library module (std/strutils), but if you don't want to do that, you'll have to implement the equivalent of parseInt yourself.

Upvotes: 4

Related Questions