0

How do one convert string type to bool data type in Nim the best way ?

 var u,o :string
 o = "ooo"
 
 if not u : # <- illusration only
itil memek cantik
  • 1,167
  • 2
  • 11

3 Answers3

3

It totally depends on what you expect to be true and false, which is why Nim doesn't provide booleaness for strings by default. This is very similar to a question we had very recently at the forum about arrays: https://forum.nim-lang.org/t/8906.

Essentially you need to define yourself what true and false means for strings. Judging from the above I'm guessing that you might want if u.len != 0. Note that strings in Nim can't be nil, so an uninitialized string is the same as an empty string. If you need to be able to tell uninitialized strings from initialized ones then you need to use the options module.

PMunch
  • 1,525
  • 11
  • 20
  • 1
    Also strutils.isEmptyOrWhitespace might be useful (another example of what is true or false for a string depends). BTW, forum link seems dead, but it's still on search: https://forum.nim-lang.org/search?q=Array%20type%20to%20boolean%20type%20conversion – xbello Feb 17 '22 at 19:24
1

You might be looking for converters: https://nim-lang.org/docs/manual.html#converters

Note that in Nim, doing so is discouraged and you should be using something along the lines of this:

let s = "abc"
if s != "":
    # code here
Davide Galilei
  • 484
  • 6
  • 9
1

You can use strutils.parseBool:

import strutils

let
    a = "n"
    b = "true"

if parseBool(a):
    echo "a is true"
else:
    echo "a is false"

if parseBool(b):
    echo "b is true"
else:
    echo "b is false"
Grzegorz Adam Hankiewicz
  • 7,349
  • 1
  • 36
  • 78