Re: [Seed7-users] string parse
Interpreter and compiler for the Seed7 programming language.
Brought to you by:
thomas_mertes
From: Thomas M. <tho...@gm...> - 2024-12-10 11:53:18
|
Hi Simon, The parse operator is the inverse operation of the str() function. The parse operator converts a string to the given type. Many types have a parse operator. E.g.: integer parse "12345" returns 12345 float parse "3.2425" returns 3.1415 For the sake of completeness, the type string also defines the function str() and the parse operator. Both only return their parameter. E.g.: str("hello") returns "hello" string parse "hello" returns "hello" These uses of str() and the parse operator do not make sense. But inside of templates they make sense. Inside a template you use a generic type specified by a template parameter. The template CONVERSION_CHECK below defines the function conversionOkay(). The function conversionOkay() returns TRUE if the given string stri can be successfully converted to the given type aType. $ include "seed7_05.s7i"; include "float.s7i"; const proc: CONVERSION_CHECK (in type: aType) is func begin const func boolean: conversionOkay (in string: stri, attr aType) is func result var boolean: okay is FALSE; local var aType: dest is aType.value; begin okay := succeeds(dest := aType parse stri); end func; end func; CONVERSION_CHECK(integer); CONVERSION_CHECK(float); CONVERSION_CHECK(string); const proc: main is func begin writeln(conversionOkay("1234", integer)); writeln(conversionOkay("zero", integer)); writeln(conversionOkay("3.14", float)); writeln(conversionOkay("3,14", float)); writeln(conversionOkay("hello", string)); end func; The program above writes: TRUE FALSE TRUE FALSE TRUE Best regards Thomas |