How to use string in if statement?

Is it not possible to use string in if statements? Sorry if this is a stupid question, I am not a very experienced user of GAUSS. I keep getting G0071 : Type mismatch for the second line of the following code:

whichmodel = "4f_2c";

if (whichmodel eq "2f_2c") or (whichmodel eq "2f_2c");

1 Answer



0



When using comparisons with strings, you need to use the string comparison operator $==. For example

whichmodel = "4f_2c";

if (whichmodel $== "2f_2c");
    print "We found a match!";
else;
    print "No match this time";
endif;

You can use the or statement with the string comparisons like this

whichmodel = "4f_2c";

if (whichmodel $== "2f_2c") or (whichmodel $== "4f_2c");
    print "We found a match!";
else;
    print "No match this time";
endif;

However, if your list of items gets longer, I would recommend using the GAUSS contains function. contains takes two inputs: haystack and needle. It answers the question "Can 'needle' be found in haystack. Let's modify your example to use contains

// Use the vertical string concatenation operator
// $| to make a vector of strings
models = "2f_2c" $| "4f_2c" $| "2f_4c";
whichmodel = "4f_2c";

// Does 'models' contain the value of 'whichmodel'
if contains(models, whichmodel);
    print "We found a match!";
else;
    print "No match this time";
endif;

aptech

1,773

Your Answer

1 Answer

0

When using comparisons with strings, you need to use the string comparison operator $==. For example

whichmodel = "4f_2c";

if (whichmodel $== "2f_2c");
    print "We found a match!";
else;
    print "No match this time";
endif;

You can use the or statement with the string comparisons like this

whichmodel = "4f_2c";

if (whichmodel $== "2f_2c") or (whichmodel $== "4f_2c");
    print "We found a match!";
else;
    print "No match this time";
endif;

However, if your list of items gets longer, I would recommend using the GAUSS contains function. contains takes two inputs: haystack and needle. It answers the question "Can 'needle' be found in haystack. Let's modify your example to use contains

// Use the vertical string concatenation operator
// $| to make a vector of strings
models = "2f_2c" $| "4f_2c" $| "2f_4c";
whichmodel = "4f_2c";

// Does 'models' contain the value of 'whichmodel'
if contains(models, whichmodel);
    print "We found a match!";
else;
    print "No match this time";
endif;


You must login to post answers.

Have a Specific Question?

Get a real answer from a real person

Need Support?

Get help from our friendly experts.